Skip to content

Instantly share code, notes, and snippets.

Created December 13, 2012 20:32
Show Gist options
  • Save anonymous/4279551 to your computer and use it in GitHub Desktop.
Save anonymous/4279551 to your computer and use it in GitHub Desktop.
Stalkable objects for Ember
/*jslint nomen:true */
(function (global) {
"use strict";
var Ember = global.Ember;
Ember.Mixin.prototype.detectInstance = function (object) {
var name,
mixins = object[Ember.META_KEY].mixins;
for (name in mixins) {
if (this.detect(mixins[name])) {
return true;
}
}
return false;
};
Ember.Stalkable = Ember.Mixin.create({
setUnknownProperty: function (key, value) {
var ret = this._super.apply(this, arguments);
this.observeNewProperty(key);
return ret;
},
observeNewProperty: function (key) {
var inst = this,
isProto = inst.constructor.prototype.hasOwnProperty(key),
clean,
handler = function () {
clean = !inst.modifiedProperties;
if (clean) {
inst.modifiedProperties = [ key ];
} else {
inst.modifiedProperties.push(key);
}
if (!isProto) {
inst.notifyPropertyChange("@ownProperties");
}
if (isProto) {
inst.notifyPropertyChange("@prototypeProperties");
}
inst.notifyPropertyChange("@properties");
if (clean) {
delete inst.modifiedProperties;
}
};
this.addObserver(key, this, handler);
handler();
},
setProperties: function () {
var ret;
this.modifiedProperties = [];
ret = this._super.apply(this, arguments);
delete this.modifiedProperties;
return ret;
}
});
Ember.Object.reopenClass({
create: function () {
var C = this,
ret = this._super.apply(this, arguments);
if (Ember.Stalkable.detectInstance(ret)) {
[].slice.apply(arguments).forEach(function (mixin) {
Object.keys(mixin).forEach(function (key) {
if (mixin[key] instanceof Function) { return; }
ret.observeNewProperty(key);
});
});
}
return ret;
}
});
Ember.StalkableObject = Ember.Object.extend(Ember.Stalkable);
}(this));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment