Last active
December 18, 2015 07:39
-
-
Save kisPocok/5748269 to your computer and use it in GitHub Desktop.
Inject custom code to object's methods. #JavaScript FYI: not working correctly!
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
function Player(id, name) { | |
this.id = id; | |
this.name = name; | |
this.hp = 100; | |
return this; | |
} | |
Player.prototype.attack = function(type) | |
{ | |
gameLogic.attack(this, type); | |
}; | |
Player.prototype.wound = function(amount) | |
{ | |
this.hp -= amount | |
}; | |
/** | |
* Override player object's methods with custom trigger or whatever | |
* Player.attack() will trigger a 'player.attack' event | |
*/ | |
for (var methodName in Player.prototype) { // override all prototype method | |
if (methodName !== 'contructor') { // don't need that | |
var legacyMethod = Player.prototype[methodName]; // save original function for later use | |
Player.prototype[methodName] = function() | |
{ | |
// TODO execute code before original method called | |
var result = legacyMethod.apply(this, arguments); // call the original method | |
// TODO execute code after orifinal method called | |
var eventName = 'player.' + methodName; | |
var eventParams = {params: arguments, result: result}; // pass some information to callback | |
$('body').trigger(eventName, eventParams); // TODO replace or do more stuff here | |
return result; // return the original response | |
}; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment