Skip to content

Instantly share code, notes, and snippets.

@MaherSaif
Created April 22, 2012 12:49
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save MaherSaif/2464000 to your computer and use it in GitHub Desktop.
Save MaherSaif/2464000 to your computer and use it in GitHub Desktop.
simple javascript hooks system
Expected Result:
----------------
One
Two
Three
Four
Six
// 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; }
}
}
// 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