Why does this work with $ (document) .ready, but not when it is an anonymous function?

I am starting to learn about the Module Design Pattern, so I wrote some code to try everything. What am I doing wrong?

(function() {

    var test = {
    init: function() {
        this.cacheDom();
        this.bindEvents();
    },
    cacheDom: function() {
        this.$button = $('button');
    },
    bindEvents: function() {
        this.$button.on('click', this.alertMsg);
    },
    alertMsg: function() {
        alert('Hello World');
    }

};

test.init();
})()

      

+3


source to share


1 answer


You have to put document.ready (or shorthand) inside the module to wrap any actions for which the DOM will be fully loaded:

(function() {

  var test = {
    init: function() {
      this.cacheDom();
      this.bindEvents();
    },
    cacheDom: function() {
      this.$button = $('button');
    },
    bindEvents: function() {
      this.$button.on('click', this.alertMsg);
    },
    alertMsg: function() {
      alert('Hello World');
    }

  };

  $(function() {
    test.init();
  });

})();

      

Remember, that:



$(function() {

});

      

is just $ (document) .ready shorthand.

+2


source







All Articles