How can you apply knockoutjs bindings from a model stored in html5 local storage? Using jStorage

StackOverflow https://stackoverflow.com/questions/15146931

Вопрос

I need data from the server to be available offline for my KnockOut.js ViewModel. I am using jStorage to help with my lack of knowledge of HTML5 localStorage. This is what I have tried:

var localModel = $.jStorage.get("model");
if(!localModel){//No local data found
    $.post("server/data.php",function(data){
        model = ko.mapping.toJS(data);
        $.jStorage.set("model",model);
        ko.applyBindings(new LightsViewModel(model));
    },"json");
} else {//Local data found
    ko.applyBindings(new LightsViewModel(localModel));
}

When I compare the local object and the post data they are both exactly the same. I was able to applyBindings within the actual post function but not after. Please help me out, I'm stumped!

Это было полезно?

Решение

I found the solution using a different plugin for localStorage. http://amplifyjs.com/api/request/ I used their request method in particular. This is the solution:

amplify.request.define("model","ajax",{
    url:"server/data.php",
    dataType:"json",
    type:"POST",
    cache:"persist"
});

amplify.request("model",function(data){
    model = ko.mapping.toJS(data);
    ko.applyBindings(new LightsViewModel(model));
});

While it makes the initial request a little bit slower, the page loads up extremely fast afterwards.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top