我有一个 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;
});