how to use the javascript module pattern in a real example?

后端 未结 5 1927
陌清茗
陌清茗 2021-01-31 05:59

I am trying to understand the JavaScript Module Pattern. I\'ve seen examples of what it should look like, but I don\'t understand how to use it.

For example, a few thing

5条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-31 06:39

    This is quite an opinionated subject, but I'd do it (without entirely knowing your full app and what it does), somewhat like so:

    var myApp = (function() {
    
      var someElement = $("#foo"); //some element I know I'll use lots
    
      var addMessage = function(message) {
        $.ajax({
          url: '/test',
          type: 'POST',
          dataType: "json",
          data: {'message' : message},
          success: function(data) {
                  ...
          },
          error: function() {
              ...
          }
        });
      };
    
      var inputClick = function(event) {
        event.preventDefault();
        //depending on if you'll reuse these selectors throughout the app I might have these as variables
        $('.loading').html('');
    
        var message = $(".wallmessage").val();
    
        if (message == ""){
          $("#messageempty").jmNotify();
          $('.remove_loading').remove();
        } else {
          addMessage(message);
        }
      };
    
      var bindFunctions = function() {
        $("input#share").on("click", inputClick)
      };
    
      var init = function() {
        bindFunctions();
      };
    
      return {
        // EDIT: 27/12/16 - need to return init for 'usage' example to work
        init: init,
        addMessage: addMessage
        //anything else you want available
        //through myApp.function()
        //or expose variables here too
      };
    
    
    })();
    
    //usage
    
    myApp.init();
    

    Your original code for the pattern is wrong, the function has to have () at the very end, to make it a function that is immediately invoked, and then executes, exposing anything through the return statement.

    You may wish to differ slightly from what I've done, it's only a basic idea but I hope it might get you started.

    Someone a while back asked a question relating to this pattern and I answered it explaining why we use (function() {})(); and how the return statement works in that context, if you're slightly confused by it that might be worth reading too.

提交回复
热议问题