-
-
Save pwFoo/86c77699893d38e9460279afa0247ed9 to your computer and use it in GitHub Desktop.
simple javascript hooks system
This file contains hidden or 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
Expected Result: | |
---------------- | |
One | |
Two | |
Three | |
Four | |
Six |
This file contains hidden or 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
// source: Jon Hobbs @http://www.velvetcache.org/ | |
var Hook = { | |
hooks: [], | |
register: function ( name, callback ) { | |
if( 'undefined' == typeof( Hook.hooks[name] ) ) | |
Hook.hooks[name] = [] | |
Hook.hooks[name].push( callback ) | |
}, | |
call: function ( name, arguments ) { | |
if( 'undefined' != typeof( Hook.hooks[name] ) ) | |
for( i = 0; i < Hook.hooks[name].length; ++i ) | |
if( true != Hook.hooks[name][i]( arguments ) ) { break; } | |
} | |
} |
This file contains hidden or 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
// source: Jon Hobbs @http://www.velvetcache.org/ | |
function test () { | |
el = document.getElementById( 'test-area' ); | |
// Set up the hooks | |
Hook.register( 'one', function ( args ) { el.innerHTML = el.innerHTML + 'One<br/>'; return true; } ); | |
Hook.register( 'one', function ( args ) { el.innerHTML = el.innerHTML + 'Two<br/>'; return true; } ); | |
Hook.register( 'one', function ( args ) { el.innerHTML = el.innerHTML + args[0]; args[0] = 'Six<br/>'; return true; } ); | |
Hook.register( 'one', function ( args ) { el.innerHTML = el.innerHTML + 'Four<br/>'; return false; } ); | |
Hook.register( 'one', function ( args ) { el.innerHTML = el.innerHTML + 'Five<br/>'; return true; } ); | |
// Set up the arguments | |
arguments = [ 'Three<br/>' ]; | |
// Call the hooks | |
Hook.call( 'one', [ 'Three<br/>' ] ); | |
// Prove the arguments were changed | |
el.innerHTML = el.innerHTML + arguments[0]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment