Question

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!

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top