1

我有一个 Backbone 模型,它的一些依赖项是通过 require JS 加载的。我正在以这种方式处理它以解决 Require.js 的循环依赖问题。(我们有多个文件需要模型、集合和视图,其中一些是循环的。)

问题是模型 ( this)上设置的属性undefined在 require 语句之外出现。代码在这里:

define(["jquery", "backbone"],
function($, Backbone) {
    var Model = Backbone.Model.extend({

        initialize: function(options) {
            var that = this;
            require(["collections/agenciesCollection", "collections/usersCollection", "models/userModel"], function(Agencies, Users, User) {
                that.agencies = (!options || !options.agencies) ? new Agencies() : new Agencies(options.agencies);
                that.users = (!options || options.users) ? new Users() : new Users(options.users); 
                if(!options || !options.contact) that.set("contact", new User()); else that.set("contact", new User(options.contact));
                if(!options || !options.admin) that.set("admin", new User()); else that.set("admin", new User(options.contact));
                console.log(that.agencies); // This is set to a collection
            });
            console.log(this.agencies); // This is 'undefined'
            console.log(this); // This has an attribute "agencies" listed in Chrome inspector
        }
  return Model;
});
4

1 回答 1

3

require在构造函数中使用异步调用,因此在您尝试将值记录到控制台时尚未定义属性。

这些行:

console.log(this.agencies); // This is 'undefined'
console.log(this); // This has an attribute "agencies" listed in Chrome inspector

在此之前执行:

console.log(that.agencies); // This is set to a collection

更新

根据您的最后评论,我想给您一个示例,说明如何简化模块定义依赖项列表。您可以尝试像这样要求您的依赖项:

define(function (require) {
  var $ = require("jquery");
      backbone = require("backbone");
      agencies = require("collections/agenciesCollection");
      users = require("collections/usersCollection");
      userModel = require("models/userModel");

  // TODO: define your exports using the required dependencies
});

这也可能有助于解释加载依赖项的不同方式:https ://github.com/jrburke/requirejs/wiki/Differences-between-the-simplified-CommonJS-wrapper-and-standard-AMD-define

于 2013-05-15T17:45:09.687 回答