11

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

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

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

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

当我尝试初始化它时,我_prepareModel()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()的类型看起来是,实际上是未定义的。thischildthis.model

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

4

2 回答 2

18

在我的实际代码Foo中是在FooCollection. 没有意识到 Javascript 不支持前向声明。[总台]

于 2013-01-04T19:00:47.230 回答
1

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

<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>

干杯

于 2015-03-03T23:54:35.880 回答