Last active
August 29, 2015 14:15
-
-
Save DmitryMyadzelets/c6081225f3a76a49fd35 to your computer and use it in GitHub Desktop.
Simple observer of object's methods
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Sets a hook for a method call for the given object. Acts as a simple observer of object's methods. | |
* @param {Object} object An object. | |
* @param {Function} method A method of the object. | |
* @param {Function} hook A callback function which will be called after the call of object's method. | |
* @param {Function} [context] Context which will passed to the hook instead of `this`. | |
* @return {Function} after Returns itself for chained calls. | |
*/ | |
function after(object, method, hook, that) { | |
var old = object[method]; | |
if (typeof old !== 'function' || typeof hook !== 'function') { | |
throw new Error('the parameters must be functions'); | |
} | |
object[method] = function () { | |
that = that || this; | |
var ret = old.apply(this, arguments); | |
hook.apply(that, arguments); | |
return ret; | |
}; | |
return after; | |
} | |
// Example | |
// Constructor | |
function Person(name) { | |
this.name = name; | |
// The instance method | |
this.smile = function () { | |
console.log(':-)'); | |
}; | |
} | |
// The prototype method | |
Person.prototype.say = function () { | |
console.log("I'm", this.name); | |
}; | |
var bob = new Person('Bob'); | |
var ali = new Person('Ali'); | |
// Hook function | |
function said() { | |
console.log(this.name, 'has just said something'); | |
} | |
// Another hook function | |
function again() { | |
console.log('We can hear', this.name); | |
} | |
// Yet another hook | |
function smiling() { | |
console.log(this.name, 'is smiling'); | |
} | |
// Set a hook for prototype method | |
after(bob, 'say', said); | |
// Sure, we can chain hooks | |
after(bob, 'say', again); | |
// A hook for instance method | |
after(ali, 'smile', smiling); | |
bob.say(); | |
// I'm Bob | |
// Bob has just said something | |
// We can hear Bob | |
bob.smile(); | |
// :-) | |
ali.say(); | |
// I'm Ali | |
ali.smile(); | |
// :-) | |
// Ali is smiling |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment