“Uncaught TypeError:undefined不是函数”初始化Backbone集合

时间:2013-01-04 18:16:33

标签: backbone.js

我有一个Backbone集合,如下所示:

var FooCollection = Backbone.Collection.extend({
    model:Foo,

    initialize: function (attributes, options) {
        this.barId = options.barId;
    }
});

var Foo = Backbone.Model.extend({});

当我尝试初始化时,我在_prepareModel()的{​​{1}}函数中得到“未捕获的TypeError:undefined不是函数”。

错误的通话在Backbone.Collection

model = new this.model(attrs, options)

当我在调试器中单步执行// Prepare a model or hash of attributes to be added to this collection. _prepareModel: function(model, options) { options || (options = {}); if (!(model instanceof Model)) { var attrs = model; options.collection = this; model = new this.model(attrs, options); // <-- BLOWS UP HERE if (!model._validate(model.attributes, options)) model = false; } else if (!model.collection) { model.collection = this; } return model; }, 时,此时_prepareModel()的类型似乎为this,而child实际上是未定义的。

谁能告诉我我做错了什么?

2 个答案:

答案 0 :(得分:17)

我的实际代码Foo是在FooCollection之后声明的。没有意识到Javascript不支持前向声明。的 [headdesk]

答案 1 :(得分:0)

我遇到了同样的问题。我的问题是我在收集脚本之后包含了我的模型脚本:

<script src="scripts/collections/Classes.js"></script>
<script src="scripts/models/Class.js"></script>

要修复它,我只需要将Class.js移到Classes.js上面:

<script src="scripts/models/Class.js"></script>
<script src="scripts/collections/Classes.js"></script>

干杯