1

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!

Marz
  • 381
  • 5
  • 10
  • What do you mean "within the post function but not after?" The second applyBindings doesn't work? – Kyeotic Feb 28 '13 at 22:41
  • Yeah, like, when I $.post to the server to get the data I can set the localStorage key named "model" and then query it inside of the $.post and the bindings will work. But yeah, when I get to the else, the bindings don't work – Marz Feb 28 '13 at 22:50

1 Answers1

1

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.

Marz
  • 381
  • 5
  • 10