javascript - Backbone Collection 和 Marionette CompositeView 中未定义的模型原型(prototype)

标签 javascript backbone.js prototype undefined marionette

尝试从值列表填充集合时,我收到有关集合的 modelprototype 未定义的错误。看着this question about a similar problem ,我已经尽我最大的能力检查了模型是否在实例化集合之前 实际创建。

在从服务器获取数据并尝试使用来自应该填充到其中的数据。

注意:使用 Backbone 0.9.10

模型

MyItemModel = Backbone.Model.extend({});

收藏

MyCollection = Backbone.Collection.extend({
    model: MyItemModel
});

CompositeView的相关代码

MyCompositeView = Backbone.Marionette.CompositeView.extend({

    initialize: function(options) {
        _.bindAll(this);
        this.model = new MyCompositeViewModel();
        this.collection = new MyCollection();
    },

    //This event handler gets properly fired and run.
    on_event: function() {
        var that = this;

        // The data comes through fine with this `fetch`
        this.model.fetch({success: function() {
            var collection_results= that.model.get("collection_results");

            // The error fires in this line
            that.collection.reset(collection_results);
            that.render();
        });
    }
})

错误

错误发生在 Backbone 的 add 函数中,当对模型对象执行 get 时,检查它是否重复。失败的代码在这里:

// Get a model from the set by id.
get: function(obj) {
    if (obj == null) return void 0;

    // The error originates from this line
    this._idAttr || (this._idAttr = this.model.prototype.idAttribute);
    return this._byId[obj.id || obj.cid || obj[this._idAttr] || obj];
},

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

此处,this.model.prototype.idAttribute 失败,因为未定义模型的 prototype

为什么会发生这种情况,如何解决?

非常感谢!

最佳答案

原因是,在 Babkbone 0.9.10 中,如果您在没有选项的情况下调用 collection.reset(models),模型将被传递给 collection.add()这严格需要真实模型作为参数。

但是,实际上,您传递的参数并不是真正的模型。它们只是哈希属性的数组。

修复的两个选项:

选项 1:使用解析选项调用重置

that.collection.reset(collection_results, {parse: true});

然后 reset 将解析哈希数组并将它们设置为模型。

选项 2:升级到最新版本的 Backbone 1.1.0。

这里reset()不再把责任交给add()而是巧妙地使用了set()。建议使用此选项。而且您在这里不需要选项。

that.collection.reset(collection_results)

另外一点

我可以建议你不要在 CompositeView 中定义 model 吗? CompositeView 是用来收集的,不是模型。当然我理解这里的模型只是为了保存和获取一些数据,但是如果代码被其他开发人员读取以及您自己维护,那将是非常困惑的。

要获取引导数据,您可以在第一次请求时加载数据,并使用常规方式将其放入集合中。 http://backbonejs.org/#FAQ-bootstrap

关于javascript - Backbone Collection 和 Marionette CompositeView 中未定义的模型原型(prototype),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20709469/

相关文章:

javascript - 无法在 Node.js 中将值 POST 到 Express

javascript - var 未在 Angular Testing 中定义

javascript - 将 Node 路由与 Backbone 路由绑定(bind)

javascript - 为什么这个扩展不起作用?

javascript - 我不明白对象的可写和可配置属性

javascript - 当域的最后一个选项卡关闭时显示弹出窗口

javascript - 我将如何在 Vue.js 中创建启动画面?

javascript - 所有 View 逻辑都应该放在模板中吗?

collections - Backbone.js - "Syncing"集合之间的模型

Javascript 构造函数与对象字面量混淆