Skip to content

Instantly share code, notes, and snippets.

@tomdale
Created April 28, 2014 02:12
Show Gist options
  • Star 12 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tomdale/11360257 to your computer and use it in GitHub Desktop.
Save tomdale/11360257 to your computer and use it in GitHub Desktop.
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
Copy link

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