2016-11-25 47 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', 
});