2014-01-10 19 views
0

我已經將實例存儲添加到了我的主幹模型中。當我手動創建一個對象與它的工作原理,並返回一個新的或已經存在的模型。我怎樣才能將這個功能集成到骨幹集合中。 你能給我一個提示,我必須重寫哪些方法/方法?將實例存儲集成到Backbone Collection中

我的實例存儲的代碼如下所示:

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; 
     } 
    }); 
}); 

我很感謝任何想法或暗示!

回答

0

好吧,我發現我的愚蠢的錯誤。

如果有人有興趣在這樣的解決方案:

沒有什麼錯重寫構造像我一樣。它像一個魅力。您不必在主幹中覆蓋任何其他方法。

但是您必須正確設置集合的模型屬性。那是我的錯誤。我沒有。

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(); 
     } 
    }); 
});