Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Ember Array that writes every change to localStorage
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);
}
});
@fsmanuel

This comment has been minimized.

Copy link

@fsmanuel fsmanuel commented Feb 2, 2015

Great work. I took the idea and made an ember-cli addon: https://github.com/funkensturm/ember-local-storage

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment