从 Json 文件收集主干并缓存在 localstorage 上 [英] Backbone collection from Json file and cache on localstorage

查看:17
本文介绍了从 Json 文件收集主干并缓存在 localstorage 上的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在主干库中相对较新.我正在尝试构建一个基于主干 + requirejs + jquery-mobile 的移动应用程序.我可以用现有的 json 本地文件填充我的收藏.(将来可能来自远程服务器).现在我试图让这个集合只被调用一次,然后将它存储在 localStorage 中以供读取.为此,我正在尝试使用此适配器(https://github.com/jeromegn/Backbone.localStorage) 但我不明白怎么做.

I am relatively new in the backbone library. I'm trying to build a mobile application based on backbone + requirejs + jquery-mobile. I can fill my collection with existing json local file. (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. for this I am trying to use this adapter (https://github.com/jeromegn/Backbone.localStorage) but I do not understand how.

// 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;
});

谁能给我指路.

推荐答案

Backbone 本地存储适配器覆盖了 Collection.sync,该函数在您 fetch集合,或 save 模型在集合中.如果您设置 Collection.localStorage 属性,它会将调用重定向到本地存储而不是服务器.这意味着您可以选择或——读取和写入本地存储或服务器——但不能同时进行.

The Backbone local storage adapter overrides Collection.sync, the function which is used when you fetch the collection, or save models within the collection. If you set the Collection.localStorage property, it redirects the calls to the local storage instead of the server. 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. 执行初始fetch,从服务器填充数据,然后才设置localStorage属性:

  1. Do the initial fetch, which populates the data from the server, and only then set the localStorage property:

var self = this;

self.collection.fetch().done(function() {
    self.collection.localStorage = new Backbone.LocalStorage("AzStore");
    self.render();
}); 

  • 像现在一样设置 Collection.localStorage 属性,并使用 Backbone.ajaxSync 手动获取初始数据集,这是给 Backbone.sync 由本地存储适配器:

  • 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:

    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() { ... });
    

    而当你想使用本地存储时,你可以使用原生的fetch:

    And when you want to use the local storage, you can use the native fetch:

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

    编辑以更正示例代码中的错误,以方便路过的 google 员工.

    Edited to correct mistake in sample code for the benefit of drive-by googlers.

    这篇关于从 Json 文件收集主干并缓存在 localstorage 上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆