backbone.js模块定义问题

backbone.js Issue with module defining

本文关键字:问题 定义 模块 js backbone      更新时间:2023-09-26

我按照这个模式来组织我的js应用程序。

正如该示例所说,我们的应用程序应该只有一个入口点。文件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'));

这似乎很好,但如果尝试定义聊天模块并稍后调用它,我会出现以下错误:

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

我认为当chat-module.js还不可用时,jQuery ready会调用该错误。我该如何解决这个问题?

您的代码创建一个对象并将其分配给全局变量chat,该变量具有module函数作为属性:

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

但当你使用它时,你会使用Application.module而不是chat.module

Application.module('Chat')

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

在我看来,您的chat变量应该称为Application

还要注意,您使用module的方式有两种,一种是使用new,另一种是不使用没有将是基于您的代码的正确使用。它将双向工作,因为module返回一个函数(它是一个对象),因此这将覆盖正常的new行为,但这意味着使用new没有任何用途,并且会误导阅读代码的人。