Javascript Hook System
Okay, so I have written a little hook/plugin system for Javascript as I needed to have a base class which other developers could then hook their functions into prior to other functionality running.
Heres what I got:
var ClassName = function(){
//Construct Stuff
}
ClassName.prototype.hooks = new Array();
ClassName.prototype.setHook = function( hook, args ){
// {Hook Name : { Func: args }}
InstanceOfClass.hooks.push({'hook': hook, 'args': args});
}
ClassName.prototype.getHook = function( hook ){
var hookArray = InstanceOfClass.getHooks();
for( var i in hookArray ){
if( hookArray[i].hook == hook ){
var argsKeys = Object.keys(hookArray[i].args);
return InstanceOfClass[argsKeys[0]].apply(ClassName, hookArray[i].args);
}
}
return null;
}
ClassName.prototype.getHooks = function(){
return InstanceOfClass.hooks;
}
Usage:
ClassName.prototype.preMethod = function(){
var InstanceOfClass = new ClassName();
InstanceOfClass.setHook('MY_HOOK', {'SomeOtherMethod', [params]});
}
ClassName.prototype.myMethod = function(){
var InstanceOfClass = new ClassName();
// Will fire off the method by hook
InstanceOfClass.getHook('MY_HOOK');
}
Please bare in mind that my JavaScript skills are very poor and there may be better ways of doing this, but I couldn't really figure anything else out.
Let me know what you think or any improvements you would make.
Written by Richard Clifford
Related protips
1 Response
WP JS Hooks is a great example of a lightweight event manager for JavaScript. Although written to mimic WordPress hooks and filters, it can be adapted to whatever your needs are. Check it out! WP JS Hooks
over 1 year ago
·
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Prototyping
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#