Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/448.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 将实例存储集成到主干集合中_Javascript_Backbone.js_Backbone.js Collections - Fatal编程技术网

Javascript 将实例存储集成到主干集合中

Javascript 将实例存储集成到主干集合中,javascript,backbone.js,backbone.js-collections,Javascript,Backbone.js,Backbone.js Collections,我已经在主干模型中添加了一个实例存储。当我手动创建一个id为的对象时,它工作并返回一个新的或已经存在的模型。如何将此功能集成到主干集合中。 你能给我一个提示,我必须重写哪些方法吗 我的实例存储代码如下所示: define(function(require) { var Backbone = require('backbone'); return Backbone.Model.extend({ constructor: function(attributes, op

我已经在主干模型中添加了一个实例存储。当我手动创建一个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;
        }
    });
});

我很感激任何想法或暗示

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

如果有人对此类解决方案感兴趣:

像我那样重写构造函数没有什么错。它就像一个符咒。您不必重写主干中的任何其他方法

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

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();
        }
    });
});
定义(功能(需要){
var Base=require('collections/Base'),
类别=要求(“型号/类别”);
return Base.extend({
型号:类别//