2016-11-25 46 views
0

我有一個集合,它從URL中提取數據。一個Backbone集合中的LocalStorage和URL

BarCollection = Backbone.Collection.extend({ 
    model: BarModel, 
    url: // Some URL 
}); 

但問題是我想從這個集合中取數據到這個集合,不僅來自URL,而且來自本地存儲。我希望我可以做這樣的事情:

BarCollection = Backbone.Collection.extend({ 
    model: BarModel, 
    url: // Some URL, 
    localStorage: new Backbone.LocalStorage('bars') 
}); 

.fetch()方法不能同時從URL和本地存儲中獲取數據。

簡單的解決方法是創建兩個不同的集合:一個用於URL,一個用於本地存儲。提取後合併它們。

BarCollection = Backbone.Collection.extend({ 
    model: BarModel, 
    url: // Some URL 
}); 

LocalBarCollection = Backbone.Collection.extend({ 
    model: BarModel, 
    localStorage: new Backbone.LocalStorage('local-contributors') 
}); 

我不知道是否有這樣做的更華麗的方式。

+0

你有我給你會要我解決的技術有任何疑問? –

回答

0

要啓用任何集合或模型從localStorage的和服務器都同步,骨幹網的同步功能可以重寫:

Backbone.sync = (function(sync) { 
    return function(method, model, options) { 
     options = options || {}; 
     var key = _.result(model, 'localStorage'), 
      response; 

     // if the localStorage property exist on the model/collection 
     // first try to sync with the localStorage 
     if (key) { 
      switch (method) { 
       case 'create': 
       case 'update': 
        var data = model.toJSON(), 
         text = JSON.stringify(data); 
        localStorage.setItem(key, text); 
        break; 
       case 'delete': 
        localStorage.removeItem(key); 
        break; 
       case 'read': 
        response = JSON.parse(localStorage.getItem(key)); 
        if (response) model.set(response, { parse: true }); 
        break; 
      } 
     } 

     // then, always sync with the server as it normally would 
     return sync.apply(this, arguments); 
    }; 
})(Backbone.sync); 

這樣,如果一個模型或集合作爲一個localStorage屬性,它我將首先與localStorage同步,然後它會進行原始同步。

例模型和收集:

var BarModel = Backbone.Model.extend({ 
    urlRoot: 'some/url', 
    localStorage: function() { 
     return 'bars-' + this.id; 
    }, 
}); 

var BarCollection = Backbone.Collection.extend({ 
    model: BarModel, 
    url: '/some/url', 
    localStorage: 'bars', 
});