Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EmberJS History/Undo

Edit: I've made my own implementation which is on GitHub

I was wondering, is there a built-in feature in ember that allows to save states of objects/arrays? In our app we've built our own undo/history implementation for a particular Ember.ArrayController, but it seems to be buggy and slow (in Firefox). So I'm wondering if there's anything out there that would replace our script.

Basically what we use it for: Users add, edit, modify elements in that array and sometimes they'd like to undo/redo their changes. At the moment we limit the amount of states to 30 (may not be the optimal amount).

Any thoughts/links are appreciated!

like image 836
Ignas Avatar asked May 11 '12 13:05

Ignas


1 Answers

I've implemented a mixin "Memento" which tracks changes of the properties defined in mementoProperties array. It supports normal properties as well as array properties.

The basic idea is the following: when the mixin is initialized, it registers itself as observer for property changes. A property change adds a new item to the memento array which represents the history of changes made. Invoking undo sets the property to the state before the change has been made. redo respectively resets the value.

The mixin is hosted on GitHub at ember-memento. It can be used as follows, see http://jsfiddle.net/pangratz666/9fa95/:

App.obj = Ember.Object.create(Ember.Memento, {
    name: 'hello',
    myArray: [],
    age: 12,

    mementoProperties: 'name age myArray'.w()
});

App.obj.get('myArray').pushObject(1);
App.obj.get('myArray').pushObject(2);
App.obj.get('myArray').pushObject(3);
App.obj.set('name', 'hubert');
App.obj.get('myArray').pushObject(4);
App.obj.set('age', 190);
App.obj.get('myArray').pushObjects(['a', 'b']);

App.obj.undo(); // myArray = [1,2,3,4]
App.obj.undo(); // age = 12
App.obj.undo(); // myArray = [1,2,3]
App.obj.undo(); // name = 'hello'
App.obj.redo(); // name = 'hubert'
App.obj.redo(); // myArray = [1,2,3,4]
App.obj.redo(); // age = 190
like image 120
pangratz Avatar answered Nov 07 '22 02:11

pangratz