Skip to content

Instantly share code, notes, and snippets.

@pjlammertyn
Created August 8, 2012 12:51
Show Gist options
  • Save pjlammertyn/3294878 to your computer and use it in GitHub Desktop.
Save pjlammertyn/3294878 to your computer and use it in GitHub Desktop.
Ember.Editable mixin
Ember.Editable = Ember.Mixin.create({
_originalPropertyStates: Ember.Map.create(),
_isEditing: false,
willDestroy: function () {
var $this = this;
for (var prop in this.getOwnProperties()) {
Ember.removeBeforeObserver($this, prop, $this, '_beforePropertyChange');
//Ember.removeObserver($this, prop, $this, '_propertyChanged');
}
},
startEditing: function () {
if (this.get('_isEditing')) {
return;
}
this.set('_isEditing', true);
this.set('_originalPropertyStates', Ember.Map.create());
var $this = this;
for (var prop in this.getOwnProperties()) {
Ember.addBeforeObserver($this, prop, $this, '_beforePropertyChange');
//Ember.addObserver($this, prop, $this, '_propertyChanged');
}
},
_beforePropertyChange: function (obj, propName) {
var origProps = this.get('_originalPropertyStates');
if (!origProps.has(propName)) {
origProps.set(propName, Ember.get(obj, propName));
this.notifyPropertyChange('isDirty');
}
},
cancelEditing: function () {
var $this = this;
this.get('_originalPropertyStates').forEach(function (key, value) {
$this.set(key, value);
});
this.endEditing();
},
endEditing: function () {
this.set('_isEditing', false);
var $this = this;
for (var prop in this.getOwnProperties()) {
Ember.removeBeforeObserver($this, prop, $this, '_beforePropertyChange');
}
this.set('_originalPropertyStates', Ember.Map.create());
},
dirtyProps: function () {
if (!this.get('_isEditing')) {
return Ember.A();
}
return this.get('_originalPropertyStates.keys.list');
}.property(),
isDirty: function () {
if (!this.get('_isEditing')) {
return false;
}
var changedPropKeys = this.get('_originalPropertyStates.keys');
if (!Ember.empty(changedPropKeys)) {
return !changedPropKeys.isEmpty();
}
return false;
}.property()
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment