Skip to content

Instantly share code, notes, and snippets.

@afonsomatos
Last active August 29, 2015 14:12
Show Gist options
  • Save afonsomatos/c3f1f9807a80bf169a47 to your computer and use it in GitHub Desktop.
Save afonsomatos/c3f1f9807a80bf169a47 to your computer and use it in GitHub Desktop.
Object.when implementation in ES5
/*!
Object-when implementation on ES5 (made by afonsomatos)
Released under the MIT license (2014-11-10)
*/
// object.when
Object.defineProperty(Object.prototype, "when", {
enumerable: false,
configurable: true,
writable: true,
value: function(prop, expect, handler) {
var expecting = expect instanceof Array ? expect : [expect]; // Don't do Array(expect) because Array(5) != [5]
var setter = function(val) {
for (var i = 0; i < expecting.length; i++) {
var possible = expecting[i] instanceof Function ? expecting[i].call(this, val) : expecting[i];
if( possible === val) {
handler.call(this, val);
// Remove the `when` listener
var temp = this[prop];
delete this[prop];
this[prop] = temp;
}
};
};
Object.defineProperty(this, prop, { set: setter });
}
});
// object.unwhen
Object.defineProperty(Object.prototype, "unwhen", {
enumerable: false,
configurable: true,
writable: true,
value: function(prop) {
// Remove the `when`listener
var temp = this[prop];
delete this[prop];
this[prop] = temp;
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment