[What is a hook]
Friends who have contacted WordPress know that the WP program can be executed like a hook function, of course, this PHP implementation of the hook. Similar functionality can be implemented in JavaScript.
In a word, the hook is to register a function or other sequence of actions that need to be performed to a unified portal, and the program executes these registered functions by invoking this hook.
[Why use hooks]
Many friends write functions like Window.onload, $ (document). Ready and so on, and a page with more than one write to a similar function, How do you make these functions that need to be executed in a unified portal (that is, the page only needs to perform a function like window.onload)?
At this point we can use hooks to implement, (take window.onload as an example) will therefore need to load the page when the execution functions are registered to a portal, such as:
function func1 () {// .... }function func2 (){// .... }hooks.addaction ("loaded", func1); // Add a function hooks.addaction ("Loaded", "Func2");
The above indicates that two functions are hung on the loaded hook. Then execute this hook, such as:
function (){hooks.doaction ("loaded"); }
This way, no matter how many functions hooks.addaction ("Loaded", function) are hung before, the hooks.doaction ("loaded") is uniformly executed here.
[How to implement JS hooks]
The principle is relatively simple, define a hook array, addaction when the function is push to the hook array, doaction the hook array of functions one by one call.
functionhooks (){ This. Queue =NewArray ();}hooks.prototype.addAction=function(Hook, func){ This. Queue[hook] =NewArray ();if(typeofFunc = = ' function ') { This. Queue[hook].push (func);} Else if(typeofFunc = = ' String ') { This. Queue[hook].push ( This. Window[func]);}}hooks.prototype.doAction=function(Hook){varParameters = Array.prototype.slice.call (arguments, 1);varfunctions = This. Queue[hook]; for(vari=0; i < functions.length; i++){ This. Call_user_func_array (functions[i], parameters);}return true;}Hooks.prototype.call_user_func_array=function(CB, parameters){if(typeofcb = = = ' String ') {func= (typeof This[CB] = = = ' function ')? This[CB]: Func = (Newfunction (NULL, ' return ' +CB)) ();} Else if(CBinstanceofArray) {func= (typeofCb[0] = = ' string ')? Eval (cb[0]+ "['" "+cb[1]+" '] "): Func = cb[0][cb[1]];} Else if(typeofcb = = = ' function ') {func=CB;}if(typeofFunc! = ' function ') {Throw NewError (func + ' is not a valid function ');}if(typeofParameters = = ' undefined ') {varTmp_ary = [];varParameters = Array.prototype.slice.call (tmp_ary, 1); }return(typeofCb[0] = = = ' String ')? Func.apply (eval (cb[0]), parameters):. ( typeofCb[0]!== ' object ')? Func.apply (NULL, parameters): func.apply (cb[0], parameters);}
The mechanism and implementation of JS hooks