简体   繁体   English

骨架.js模块定义的问题

[英]backbone.js Issue with module defining

I follow this pattern to organize my js application. 我遵循这种模式来组织我的js应用程序。

As that example says our application should has the single entry point. 如该示例所述,我们的应用程序应具有单个入口点。 File application.js doing that work. 文件application.js可以完成这项工作。

// Filename: application.js

var chat = {
  // Create this closure to contain the cached modules
  module: function() {
    // Internal module cache.
    var modules = {};

    // Create a new module reference scaffold or load an
    // existing module.
    return function(name) {
      // If this module has already been created, return it.
      if (modules[name]) {
        return modules[name];
      }

      // Create a module and save it under this name
      return modules[name] = { Views: {} };
    };
  }()
};

// Using the jQuery ready event is excellent for ensuring all 
// code has been downloaded and evaluated and is ready to be 
// initialized. Treat this as your single entry point into the 
// application.
jQuery(function($) {

  $(document).ready(function(){
    var foo = new Application.module('Chat').Collection();
 }); 
});


// Filename: chat-module.js

(function(chat){
  chat.Model = Backbone.Model.extend({ ... }),
  chat.Collection = Backbone.Collection.extend({ ... }),
})(Application.module('Chat'));

It seems well but if try to define chat module for example and invoke it later I have the following error: 看起来不错,但是如果尝试例如定义聊天模块并稍后调用它,则会出现以下错误:

Uncaught TypeError: Property 'Collection' of object #<Object> is not a function

I think that error due jQuery ready invokes when chat-module.js not available yet. 我认为当chat-module.js尚不可用时,由于jQuery ready会引发该错误。 How can I resolve that problem? 我该如何解决这个问题?

Your code creates an object and assigns it to the global variable chat , which has a module function as a property: 您的代码创建一个对象,并将其分配给全局变量chat ,该变量具有module功能作为属性:

var chat = {
    module: function...
};

...but then when you use it, you use Application.module rather than chat.module . ...但是当您使用它时,可以使用Application.module而不是chat.module

Application.module('Chat')

and

var foo = new Application.module('Chat').Collection();

It seems to me that your chat variable should be called Application . 在我看来,您的chat变量应称为Application

Also note that you're using module in two different ways, both with new and without. 还要注意,您以两种不同的方式使用module ,包括new和not。 Without would be the correct use based on your code. 没有将根据您的代码正确使用。 It will work both ways because module returns a function (which is an object), and so that will override the normal new behavior, but it means that using new serves no purpose and is misleading to someone reading the code. 因为module返回一个函数(这是一个对象),所以这两种方法都可以工作,并且这将覆盖正常的new行为,但这意味着使用new毫无用处,并且会误导阅读代码的人。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM