【问题标题】:Integrate instance store into Backbone Collection将实例存储集成到主干集合中
【发布时间】:2014-01-10 20:40:35
【问题描述】:

我已将实例存储添加到我的主干模型中。当我手动创建一个带有 id 的对象时,它可以工作并返回一个新的或已经存在的模型。我如何将此功能也集成到主干集合中。 你能给我一个提示,我必须重写哪些方法/方法?

我的实例存储代码如下所示:

define(function(require) {
    var Backbone = require('backbone');
    return Backbone.Model.extend({
        constructor: function(attributes, options) {
            var id = attributes ? attributes.id : undefined;
            if(this.store[id])
                return this.store[id];
            Backbone.Model.prototype.constructor.apply(this, arguments);
            if(id)
                this.store[id] = this;
            this.count[id] = this.count[id] ? this.count[id] + 1 : 1;
        }
    });
});

感谢任何想法或提示!

【问题讨论】:

    标签: javascript backbone.js backbone.js-collections


    【解决方案1】:

    好的,我发现了我的愚蠢错误。

    如果有人对这种解决方案感兴趣:

    像我一样重写构造函数并没有错。它就像一个魅力。您不必重写 Backbone 中的任何其他方法。

    但是您必须正确设置集合的模型属性。那是我的错误。我没有。

    define(function(require) {
        var Base = require('collections/base'),
            Category = require('models/category');
    
        return Base.extend({
            model: Category, //<-- Important!
            url: function() {
                return App.serverUrl + 'categories';
            },
            initialize: function() {
                this.fetch();
            }
        });
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-05
      • 2015-09-05
      • 2013-07-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多