2014-12-30 50 views
0

我試着站起來,並通過與骨幹網的localStorage運行安裝下面backbone.LocalStorage與RequireJS

https://github.com/jeromegn/Backbone.localStorage

,但我無法弄清楚如何真正將它集成到我的應用程序。我連接了我想要本地存儲的集合(saved),但Im不確定如何保存/獲取模型(重新加載時)。

(function($){ 

     require.config({ 
      paths: { 
       jquery: "//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js", 
       underscore: "//cdnjs.cloudflare.com/ajax/libs/underscore.js/1.7.0/underscore-min.js", 
       backbone: "//cdnjs.cloudflare.com/ajax/libs/backbone.js/1.1.2/backbone-min.js", 
       localStorage: "backbone.localStorage.js" 
      } 
     }); 

     define('saved', ['localstorage'], function(){ 
      var saved = Backbone.Collection.extend({ 
       localStorage: new Backbone.LocalStorage('saved') 
      }); 

      return saved; 
     }); 

     //---------SINGLE ENTRY MODEL---------- 
       var Entry = Backbone.Model.extend({ 
        defaults: function(){ 
         return{ 
          word: '', 
          definition: '' 
         } 
        } 
       }); 

     //------------ENTRY MODEL COLLECTION------------ 
     EntryList = Backbone.Collection.extend({ 

       localStorage: new Backbone.LocalStorage('saved'), 

       model: Entry 
      }); 

     //-----INSTANCIATE COLLECTION---- 
     var dictionary = new EntryList(); 
     var saved = new EntryList(); 
     . 
     . 
     . 

回答

0

其實你已經使用localStorage的,當你做這樣的事情:

//------------ENTRY MODEL COLLECTION------------ 
EntryList = Backbone.Collection.extend({ 
    localStorage: new Backbone.LocalStorage('saved'), 
    model: Entry 
}); 

你從同一收集啓動變量dictionarysaved,我猜你只想要saved是localStorage的?如果是這樣,那麼它不會是你所期望的。 這是因爲在擴展Backbone.Collection時添加localStorage: new Backbone.LocalStorage('saved')屬性時,此集合將永遠使用localStorage。

用它來保存,你只需要調用saved.create({ word: 'abc', definition: 'i dun know'}) 源獲取已保存的入口,只需saved.fetch()

example給出的方式一個很好的觀點

,您可以鍵入「localStorage的」,以檢查它是否被啓動或具有瀏覽器控制檯上的任何數據(i; M使用Chrome Devtool)