为什么这与$(document).ready一起使用,但不是在它是匿名函数时?

时间:2015-07-24 16:49:51

标签: jquery

我开始学习模块设计模式,所以我写了一些代码来尝试。我做错了什么?

(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();
})()

1 个答案:

答案 0 :(得分:2)

你应该将document.ready(或简写)放在模块中来包装任何需要完全加载DOM的动作:

 func tabBarController(tabBarController: UITabBarController, shouldSelectViewController viewController: UIViewController) -> Bool {

        if let yourViewController = tabBarController.selectedViewController as? YourViewController {
            // do something you want to do on your viewcontroller, where you are leaving from.
            // yourViewController.doSomething()
        }
        return true
    }

请记住:

(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();
  });

})();

只是$(文件).ready简写。