0

I'm getting started with backbone, I used this localStorage adapter. Here's my test code:

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

If I load the page multiple times it says loaded: undefined every time. however, after my second load I would expect loaded: abc every time. when I inspect my localstorage after 2 loads I see this:

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"}

Does anyone know what's going wrong?

Edit
I've created a jsfiddle demonstrating this (run it twice) http://jsfiddle.net/Myster/fE9eQ/3/

4

1 に答える 1

0

@tkone、あなたは私が思う正しい答えを提案しています。フェッチは非同期であるため、jquery deferreds を使用するか、成功コールバックでモデルの設定/保存を行わない限り、これが動作になります。

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();
        }
    });
});
于 2012-05-06T18:12:47.247 に答える