如何存储“集合”包括本地存储中的所有模型?(backbone.js)

How to store a "collection" including all models in the local-storage? (backbone.js)

本文关键字:存储 模型 js backbone 包括本 何存储 集合      更新时间:2023-09-26

我在外部fetch()函数中读取了一个大的xml文件,这工作得很好。我的问题是,如何将填充的集合保存到本地存储?如果本地存储已经存在,我该如何测试呢?否则将执行fetch()。我需要在哪里添加集合中的代码?save()吗?localStorage: new Backbone.LocalStorage("test_storage") ?

这个例子展示了一小段代码:

    var test_collection = Backbone.Collection.extend( .. );
    var test_collection_view = Backbone.View.extend( .. ); 

    //--------------------------------------
    // external fetch
    //--------------------------------------             
    function fetch(){
       return $.ajax({
           url: 'TestInterface.xml',
               method: 'GET',
          dataType: 'xml',
          success: function(response_xml) {
             ... //parse data to test_collection
          }//end success
       });//end ajax
    }//end fetch

    //--------------------------------------
    // Initialize
    //--------------------------------------
    $(document).ready(function(){
        $.when( fetch() ).done(function() {            
            var VIEW = new test_collection_view({collection: test_collection});
        });//end when
     });//end ready
更新:

我也可以推荐在后续步骤中使用deferred:

返回延迟承诺对象并解析

您可以使用JSON.stringify():

保存您的收藏
test_collection.fetch({
  success: function(collection, response) {
    // Store an array containing the attributes hash of each model
    // in the collection.
    var collectionJSON = collection.toJSON();
    // Store the collection as a JSON string.
    localStorage.setItem('collection', JSON.stringify(collectionJSON));
  }
});

然后,您可以使用:

检索您的集合数据:
var collectionString = localStorage.getItem('collection');
var collection = JSON.parse(collectionString);

检查集合是否已经存储:

if (localStorage.getItem('collection') !== null) {
  // ...
}
实现这一点的最佳方法是在您的fetch()例程中。首先检查集合是否已存储,如果已存储则返回,否则取出。