Skip to content

Instantly share code, notes, and snippets.

@greyarch
Created June 20, 2013 19:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save greyarch/5825965 to your computer and use it in GitHub Desktop.
Save greyarch/5825965 to your computer and use it in GitHub Desktop.
Knockout persistence to localStorage. This is a very simple way to persist the value of a knockout observable to local storage. Every time you set the value of the observable it is also stored in the localStorage. You can indeed use this mechanism with any storage system.
ko.extenders.persist = function (target, option) {
target.subscribe(function (newValue) {
window.localStorage.setItem(option, newValue);
});
return target;
};
//and use it like this:
var item = ko.observable().extend({persist:"storedItem"});
//or if you want to also initialize the observable with the stored value:
var item = ko.observable(window.localStorage.getItem("storedItem")).extend({persist:"storedItem"});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment