2012-04-26 68 views
0

我開始接觸骨幹,我用this localStorage adapter。 這裏是我的測試代碼:Backbone.js的:麻煩堅持簡單的模型來localStorage的

cartStatus = Backbone.Model.extend({ 
    localStorage: new Store("cartStatus"), 
    currentClientId: "" 
}); 

var myStatus = new cartStatus; 

$(function() { 
    myStatus.fetch(); 
    alert("loaded" + myStatus.get("currentClientId")); 
    myStatus.set({ "currentClientId": "abc" }); 
    myStatus.save(); 
}); 

如果我加載頁面多次,它說每次loaded: undefined。但是,在我第二次加載後,我預計每次都會有loaded: abc。 當我檢查我的localStorage後2個負荷我看到這一點:

cartStatus-d2a7b64d-2f15-a741-9a8c-e254b4a13682 {"0":{"currentClientId":"abc","id":"dd5e0e47-9356-ea30-2de3-75a041848b88"},"currentClientId":"abc","id":"d2a7b64d-2f15-a741-9a8c-e254b4a13682"} 
cartStatus dd5e0e47-9356-ea30-2de3-75a041848b88,d2a7b64d-2f15-a741-9a8c-e254b4a13682 
cartStatus-dd5e0e47-9356-ea30-2de3-75a041848b88 {"currentClientId":"abc","id":"dd5e0e47-9356-ea30-2de3-75a041848b88"} 

有誰知道是怎麼回事?

編輯
我創建了一個展示的jsfiddle這個(運行兩次)http://jsfiddle.net/Myster/fE9eQ/3/

+0

即使它是本地存儲,您是否嘗試過在'fetch'的'success'選項中執行alert? – tkone 2012-04-26 20:31:59

+0

成功觸發回調(見上文編輯爵士小提琴) – Myster 2012-04-30 02:44:02

回答

0

@tkone,你的建議正確的答案,我認爲。提取是異步的,所以除非你使用jQuery延遲或者在成功回調中設置/保存模型,那麼這就是行爲。

cartStatus = Backbone.Model.extend({ 
    localStorage: new Store("cartStatus"), 
    currentClientId: "" 
}); 

var myStatus = new cartStatus(); 

$(function() { 
    debugger; 
    myStatus.fetch({ 
     success: function(x) { 
      document.write('myStatus.fetch - success !<br />'); 
      myStatus.set("currentClientId", "abc"); 
      myStatus.save(); 
     } 
    }); 
}); 
+0

在這個例子中,如果我刷新頁面4次我結束了我在localStorage的4個項目(每個後續verison具有嵌套在以前的版本),在這裏我想只是要更新的一個項目。 – Myster 2012-05-06 21:48:25