diff --git a/README.md b/README.md index 0b0e84b..57fe0e3 100644 --- a/README.md +++ b/README.md @@ -17,8 +17,10 @@ the key to use when storing the value to localHost namePersist: ko.observable(null, {persist: 'namePersist'}), - nameDefaultPersist: ko.observable('James', {persist: 'nameDefaultPersis'}) - + nameDefaultPersist: ko.observable('James', {persist: 'nameDefaultPersis'}), + + // any changes to localStorage will be propagated back to the variable + synclocal : ko.observable('Jamie', {persist: 'nameTestLocal', synclocal : true, pollfreq : 500 }) } ko.applyBindings(viewModel); diff --git a/examples/index.html b/examples/index.html index 686e6fd..b1cf6ad 100644 --- a/examples/index.html +++ b/examples/index.html @@ -26,8 +26,15 @@

+ +

+ +

+ diff --git a/knockout.localStorage.js b/knockout.localStorage.js index 32280de..d1bff60 100644 --- a/knockout.localStorage.js +++ b/knockout.localStorage.js @@ -1,7 +1,13 @@ (function(ko){ + "use strict"; + + var DEFAULT_POLL_FREQUENCY = 1000; + // Wrap ko.observable and ko.observableArray var methods = ['observable', 'observableArray']; + var lastValue = {}; + ko.utils.arrayForEach(methods, function(method){ var saved = ko[method]; @@ -19,12 +25,32 @@ // Create observable from saved method var observable = saved(initialValue); + if (options.synclocal) lastValue[key] = initialValue; // Subscribe to changes, and save to localStorage if(key){ observable.subscribe(function(newValue){ localStorage.setItem(key, ko.toJSON(newValue)); + if (options.synclocal) lastValue[key] = newValue; }); + + // Be notify of the changes at the localStorage + if (options.synclocal) { + (function (observable, key) { + setInterval(function () { + try{ + var localVal = JSON.parse(localStorage.getItem(key)) + if (lastValue[key] != localVal) { + observable(localVal); + lastValue[key] = localVal; + } + }catch(e){ + console.warn(e); + }; + }, options.pollfreq || DEFAULT_POLL_FREQUENCY); + })(observable, key); + } + }; return observable;