Javascript 从JSON.file获取模型并将其存储在localstorage主干中

Javascript 从JSON.file获取模型并将其存储在localstorage主干中,javascript,jquery,json,backbone.js,Javascript,Jquery,Json,Backbone.js,上面的代码是从.JSON文件中获取数据,创建模型,甚至在console.log中成功打印出来 但我甚至必须将其存储在LOCALSTORAGE中,因为当我在控制台中打印LOCALSTORAGE时,它显示为空 我想要的是在页面上使用从.json文件获取数据,并将这些模型存储在Localstorage中,以便下次我将获取数据(即模型)从本地存储,而不是从文件。您需要覆盖集合的sync功能,将其置于逻辑中,首先检查缓存,然后从远程位置提取并更新缓存,以便后续请求将拾取缓存 Collection.fetc

上面的代码是从.JSON文件中获取数据,创建模型,甚至在console.log中成功打印出来

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


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

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

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}
});
请记住,当覆盖模型或集合的同步方法时,还必须编写逻辑来处理将使用的其他方法,例如
创建
更新
销毁

有关
sync
方法的更多信息,请参见

我还制作了一把小提琴来演示这个功能。

您是否在谈论设备本地存储,然后尝试localStorage.a=“value”(作为json字符串)是的,这将起作用,我如何在使用fetch时执行此操作,以便从json文件中获取的任何数据都将存储在LocalStorages中,如果要保存其集合,则将其作为localStorage.coll=json.stringify(集合)执行操作;并且可以根据需要获取localStorage.coll whwn(只需解析它)
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();
  }
});