init();
//model specification
function SimpleModel() {
var _this = this;
this.message = ko.observable('Hello');
this.subject = ko.observable('World');
this.text = ko.computed(function() {
return _this.message() + ' ' + _this.subject() + '!';
});
}
//new it up
var vm = new SimpleModel();
var options = {
storage: sessionStorage
};
//bind to interface
ko.applyBindings(vm);
//persist it
ko.persistChanges(vm, 'vm-', options);
//alert 1 - should be 'Hello World!'
//at leaste the first time ;-)
alert('vm: ' + vm.text());
//change it
vm.message('Bye');
//alert 2 - should be 'Bye World!'
alert('vm: ' + vm.text());
//load a new one up to check
var vm2 = new SimpleModel();
ko.persistChanges(vm2, 'vm-', options);
//alert 3 - should be 'Bye World!'
alert('vm2: ' + vm2.text());
function init() {
ko.trackChange = (store, observable, key) => {
//initialize from stored value, or if no value is stored yet,
//use the current value
const value = store.get(key) || observable()
//restore current value
observable(value)
//track the changes
observable.subscribe(newValue => store.set(key, newValue))
}
const defaultOptions = Object.freeze({
storage: localStorage,
traverseNonObservableProperties: true,
})
ko.persistChanges = (model, prefix = "model-", options = defaultOptions) => {
options = Object.assign({}, defaultOptions, options)
console.log(options)
const storageWrapper = {
set: (key, value) => options.storage.setItem(key, JSON.stringify(value)),
get: key => JSON.parse(options.storage.getItem(key)),
}
for (let n in model) {
const observable = model[n]
const key = prefix + n
if (!ko.isObservable(observable)) {
if (options.traverseNonObservableProperties) {
ko.persistChanges(observable, key + "-", options)
}
} else if (!ko.isComputed(observable)) {
//track change of observable
ko.trackChange(storageWrapper,...
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.