7

I can implement Mvvm with Knockout.js. But I want to use it with cross browser(FF and Chrome) supported Html 5 offline storage.

I want to bind html objects to offline storage.

Oguz Karadenizli
  • 3,449
  • 6
  • 38
  • 73

4 Answers4

6

I haven't tried it, but there is a knockout.localStorage project on GitHub, that seems to be what you are looking for.

With that plugin, you should be able to pass an object as a second argument, when you create your observable, which saves the observable into localStorage.

From the documentation:

var viewModel = {
  name: ko.observable('James', {persist: 'name'})
}

ko.applyBindings(viewModel);
Christofer Eliasson
  • 32,939
  • 7
  • 74
  • 103
6

You can use a library such as amplify.js which can serialize objects to localStorage (cross browser). It falls back to older storage tools for older browsers too. First, unwrap the observables to a JSON object, then use amplify.store to serialize the object and store it. Then you can pull it back out and map it back to an observable object when you want to fetch it.

http://amplifyjs.com/api/store/

John Papa
  • 21,880
  • 4
  • 61
  • 60
  • 2
    Just a note, AmplifyJS doesn't appear to support cookies from version `1.0 beta` onwards [ http://amplifyjs.com/changelog/ ] – jamiebarrow Jan 22 '13 at 23:05
2

I worked out a solution bases on the subscribe feature of KnockoutJS. It takes a model and persist all the observable properties.

ko.persistChanges = function (vm, prefix) {

    if (prefix === undefined) {
        prefix = '';
    }

    for (var n in vm) {

        var observable = vm[n];
        var key = prefix + n;

        if (ko.isObservable(observable) && !ko.isComputed(observable)) {

            //track change of observable
            ko.trackChange(observable, key);

            //force load
            observable();
        }
    }
};

Check http://keestalkstech.com/2014/02/automatic-knockout-model-persistence-offline-with-amplify/ for code and JSFiddle example.

Kees C. Bakker
  • 32,294
  • 27
  • 115
  • 203