尝试将对象添加到主干集合时,此模型未定义

时间:2013-04-20 23:12:38

标签: javascript backbone.js underscore.js

我想知道在使用骨干系列时是否还有什么需要记住的?我基本上有一个模型,我的集合定义为:

LibraryPreps = (function () {
    return Backbone.Collection.extend({
        model: LibraryPrep,
        url: '/api/platform',
        initialize: function (models, options) {

        }
    });
})();


LibraryPrep = (function () {
    return Backbone.Model.extend({

        defaults: {
            name: '',
            platform: '',
        },
        initialize: function () {
            return this;
        }
    });
})();
对他们一无所知。当我创建一个LibraryPrep并记录它时,它看起来像我想要的数据。但是当我尝试将它添加到集合中时,我收到了这个错误:

TypeError: this.model is undefined
followed by this line of code:
this._idAttr || (this._idAttr = this.model.prototype.idAttribute);

我基本上是这样做的:

var libPreps = new LibraryPreps();

            _.each(libraries, function (library) {
                console.log("POPULATE LIBRARY PREP");
                console.log(library);
                var tempLibPrep = new LibraryPrep(library);
                console.log(tempLibPrep);

                libPreps.add(tempLibPrep);    // why aren't you working?!
            });

之前我在其他地方使用过一个集合,我似乎从来没有遇到任何问题。我对网络很陌生,所以也许我只是想到了。有什么想法吗?提前致谢: - 。

2 个答案:

答案 0 :(得分:2)

看看LibraryPreps.prototype,你会看到你出错的地方。首先,您的真实代码必须看起来更像这样,否则您将获得ReferenceError s:

var LibraryPreps = (function () { ... })();
var LibraryPrep  = (function () { ... })();

当生成LibraryPreps的匿名函数执行时,LibraryPrep将被取消定义,因为直到稍后才分配值。如果你这样做:

var LibraryPreps = (function () {
    return Backbone.Collection.extend({
        model: LibraryPrep,
        //...
    });
})();
var LibraryPrep = (function () {
    return Backbone.Model.extend({ /*...*/ });
})();
console.log(LibraryPreps.prototype);

您会在控制台中看到LibraryPreps.prototype.modelundefined。演示:http://jsfiddle.net/ambiguous/y8cja/

Backbone.Collection.extend调用(带或不带匿名自执行函数包装器)强制在调用LibraryPrep时评估extend,以便最终构建集合“类“具有undefined model属性。然后,在Backbone中,它将查找集合模型的idAttribute,并且您会收到错误。

修复定义的顺序,以便在使用之前定义内容:

var LibraryPrep  = (function () { ... })();
var LibraryPreps = (function () { ... })();

你会有更好的结果。


在评论中注明Loamhoof,您的代码可以正常使用当前版本的Backbone(1.0.0),我找不到:

this._idAttr || (this._idAttr = this.model.prototype.idAttribute);

1.0.0源代码中的任何位置。据推测,您使用的是旧版本的Backbone,其Collection#add方法需要知道其模型的idAttribute属性。

答案 1 :(得分:0)

您是否尝试将模型直接添加到集合中?

libPreps.add(libraries); 

http://backbonejs.org/#Collection-add

addcollection.add(models,[options]) 将一个模型(或一组模型)添加到集合中,触发“添加”事件。如果定义了模型属性,您还可以传递原始属性对象,并将它们作为模型的实例进行活动。传递{at:index}以将模型拼接到指定索引处的集合中。如果您要将集合中的模型添加到集合中,那么它们将被忽略,除非您通过{merge:true},在这种情况下,它们的属性将合并到相应的模型中,触发任何适当的“更改”事件。