Created
April 28, 2014 02:12
-
-
Save tomdale/11360257 to your computer and use it in GitHub Desktop.
Ember Array that writes every change to localStorage
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export default Ember.ArrayProxy.extend({ | |
localStorageKey: null, | |
init: function() { | |
var localStorageKey = this.get('localStorageKey'); | |
if (!localStorageKey) { | |
throw new Error("You must specify which property name should be used to save " + this + " in localStorage by setting its localStorageKey property."); | |
} | |
// Retrieve the serialized version from localStorage using the specified | |
// key. | |
var serialized = localStorage[localStorageKey]; | |
var content; | |
// If there is a serialized array available, deserialize it and use it | |
// as the underlying array. Otherwise, create a new empty array. | |
if (serialized) { | |
content = JSON.parse(serialized); | |
} else { | |
content = []; | |
} | |
this.set('content', content); | |
return this._super.apply(this, arguments); | |
}, | |
replaceContent: function(idx, amount, objects) { | |
this._super(idx, amount, objects); | |
this.save(); | |
}, | |
save: function() { | |
var content = this.get('content'); | |
var localStorageKey = this.get('localStorageKey'); | |
localStorage[localStorageKey] = JSON.stringify(content); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Great work. I took the idea and made an ember-cli addon: https://github.com/funkensturm/ember-local-storage