【问题标题】:How to store a "collection" including all models in the local-storage? (backbone.js)如何在本地存储中存储包括所有模型的“集合”? (骨干网.js)
【发布时间】:2015-10-19 05:18:03
【问题描述】:

我在外部 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

更新:

我也可以推荐这个用于延迟的进一步步骤:

Return deferred promise object and resolve it

【问题讨论】:

    标签: javascript jquery backbone.js local-storage


    【解决方案1】:

    您可以使用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() 例程中。首先检查集合是否被存储,如果是则返回,否则获取它。

    【讨论】:

      猜你喜欢
      • 2015-07-20
      • 1970-01-01
      • 2014-04-03
      • 2013-09-24
      • 2013-11-05
      • 2014-11-30
      • 2015-10-24
      • 2013-04-30
      • 1970-01-01
      相关资源
      最近更新 更多