从JSON.file中获取模型并将其存储为localstorage Backbone

时间:2014-12-02 09:52:29

标签: javascript jquery json backbone.js

Collection.fetch().done(function(){
    console.log(Collection); // fetchs all the models and successfully print here 

    Collection.localStorage = new Backbone.LocalStorage('Localstorage');
    console.log(localStorage); // Storage {length: 0}
});

以上代码是从.JSON文件中获取数据并创建模型,甚至成功将其打印在console.log中。

但我甚至必须将其存储在 LOCALSTORAGE 中,因为当我在控制台中打印localstorage时它显示为空。

我想要的是页面加载从.json文件获取数据并使用将这些模型存储在Localstorage中,以便下次我将从localstorage 获取数据(即模型)而不是从文件中获取数据。 / p>

1 个答案:

答案 0 :(得分:0)

您需要覆盖集合的sync函数以置于逻辑中以首先检查缓存,然后从远程位置获取并更新缓存,以便后续请求将获取缓存。

var Collection = Backbone.Collection.extend({
  sync: function(method, collection, options) {
    var cache, data, dfd = $.Deferred(),
        cacheId = "collectionCache";

    switch (method) {
      case "read":

        // Attempt to get the cache
        cache = sessionStorage.getItem(cacheId);

        // Check if the cache has anything
        if (cache) {
          console.log("Returning from cache");

          // If the cache exists, call the success callback and resolve the Deferred object
          options.success(cache);
          dfd.resolve(cache)
        } else {
          console.log("Returning from external data");

          // We would perform the ajax call here to fetch our JSON
          data = externalData

          // Set the data that came from the file into our session storage
          sessionStorage.setItem(cacheId, data);

          // Call the success callback and resolve the Deferred object with the data loaded from the file
          options.success(data);
          dfd.resolve(data);
        }
        break;
    }

    // By overriding the sync function for this collection, you would also have to define logic for the create, update and destory methods.

    return dfd.promise();
  }
});

请记住,当您覆盖模型或集合的sync方法时,您还必须编写逻辑来处理将使用的其他方法,例如createupdatedestroy

有关sync方法的更多信息,请参阅Backbone's Docs

我还拼凑了一个小提琴演示这个功能。 http://jsbin.com/hazimi/1/edit?js,console