简体   繁体   English

来自Json文件的骨干集合和localstorage上的缓存

[英]Backbone collection from Json file and cache on localstorage

I am relatively new in the backbone library. 我在骨干库中比较新。 I'm trying to build a mobile application based on backbone + requirejs + jquery-mobile. 我正在尝试构建一个基于backbone + requirejs + jquery-mobile的移动应用程序。 I can fill my collection with existing json local file. 我可以使用现有的json本地文件填充我的集合。 (in the future may come from a remote server). (将来可能来自远程服务器)。 Now I'm trying to get this collection to be called only once and then storing it in localStorage for read. 现在我试图让这个集合只被调用一次,然后将它存储在localStorage中进行读取。 for this I am trying to use this adapter ( https://github.com/jeromegn/Backbone.localStorage ) but I do not understand how. 为此,我试图使用这个适配器( https://github.com/jeromegn/Backbone.localStorage ),但我不明白如何。

Sample code 示例代码

// models
define([
  'underscore',
  'backbone'
], function(_, Backbone) {
  var AzModel = Backbone.Model.extend({
    defaults: {
      item: '',
      img:"img/gi.jpg"
    },
    initialize: function(){
    }
  });
  return AzModel;
});

// Collection
define(['jquery', 'underscore', 'backbone', 'models/az'], function($, _, Backbone, AzModel) {
    var AzCollection = Backbone.Collection.extend({
     localStorage: new Backbone.LocalStorage("AzStore"), // Unique name within your app.       
    url : "json/azlist.json",
    model : AzModel
    parse : function(response) {
         return response;
    }
});

return AzCollection;
});

define(['jquery', 'underscore', 'backbone', 'collections/azlist', 'text!templates/karate/az.html'], function($, _, Backbone, AzList, AzViewTemplate) {
    var AzView = Backbone.View.extend({
        id:"az",
        initialize: function() {
            this.collection = new AzList(); 
            var self = this;
            this.collection.fetch().done(function() {
                //alert("done")
                self.render();
            }); 

        },
        render : function() {
            var data = this.collection;
            if (data.length == 0) {
                // Show's the jQuery Mobile loading icon
                $.mobile.loading("show");
            } else {
                 $.mobile.loading("hide");
                console.log(data.toJSON());
                  this.$el.html(_.template(AzViewTemplate, {data:data.toJSON()}));
                  // create jqueryui
                 $(document).trigger("create");
            }
            return this;
        }
    });
    return AzView;
});

Does someone can point me the way. 有人可以指路吗?

The Backbone local storage adapter overrides Collection.sync , the function which is used when you fetch the collection, or save models within the collection. Backbone本地存储适配器会覆盖Collection.sync ,该函数在您fetch集合时使用,或者在集合中save模型。 If you set the Collection.localStorage property, it redirects the calls to the local storage instead of the server. 如果设置Collection.localStorage属性,则会将调用重定向到本地存储而不是服务器。 This means you can have either or -- read and write to local storage or server -- but not both at the same time. 这意味着您可以使用或 - 读取和写入本地存储或服务器 - 但不能同时读取和写入本地存储或服务器。

This leaves you two options: 这有两个选择:

  1. Do the initial fetch , which populates the data from the server, and only then set the localStorage property: 执行初始fetch ,从服务器填充数据,然后设置localStorage属性:

     var self = this; self.collection.fetch().done(function() { self.collection.localStorage = new Backbone.LocalStorage("AzStore"); self.render(); }); 
  2. Set the Collection.localStorage property as you do now, and fetch the initial dataset manually using Backbone.ajaxSync , which is the alias given to Backbone.sync by the localstorage adapter: 像现在一样设置Collection.localStorage属性,并使用Backbone.ajaxSync手动获取初始数据集, Backbone.sync是localstorage适配器为Backbone.sync的别名:

     Backbone.ajaxSync('read', self.collection).done(function() { self.render(); } 

The latter option might be preferrable, because it doesn't prevent you from loading the data from the server later on, if required. 后一个选项可能是首选的,因为它不会阻止您稍后从服务器加载数据(如果需要)。

You could quite neatly wrap the functionality as a method on the collection: 您可以将功能整齐地包装为集合上的方法:

var AzCollection = Backbone.Collection.extend({
    localStorage: new Backbone.LocalStorage('AzStore'),
    refreshFromServer: function() {
        return Backbone.ajaxSync('read', this);    
    }    
});

When you want to load data from the server, you can call that method: 如果要从服务器加载数据,可以调用该方法:

collection.refreshFromServer().done(function() { ... });

And when you want to use the local storage, you can use the native fetch : 当您想使用本地存储时,您可以使用本机fetch

collection.fetch().done(function() { ... });

Edited to correct mistake in sample code for the benefit of drive-by googlers. 编辑以纠正示例代码中的错误,以便驾车的googlers受益。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM