jQuery hook, event message passing, callback function

Jonathan Hendler

on

May 22, 2007

jQuery hook, event message passing, callback function

Do you like Drupal's hook functionality?
Maybe this jQuery extension could serve as a way to replicate that that functionality. Currently I use the extension below to allow the extension of existing libraries I've written.

Let's say in your library you write :
  if (confirmed){
    $('#css-id').hide(
      function(){
         $.hookExecute('css_id_hidden');
      }
    );
  }

One function in a new libarary could write
  function css_id_hidden(){
    alert('Hidden!');
  }

And a different developer
  function css_id_hidden(){
    $('#other-css-id').html('The area is hidden.');
  }

Here's the code:
/**
 * a jquery hook function
 * 
 * lets a current js function call alternate functions
 * 
 * @todo mimic drupal hook system
 * 
 * @author Jonathan Hendler (jonathan at civicactions dot com)
 * @license AGPL http://www.affero.org/oagpl.html
 * @version 0.1.0
 * 
 *  hookExecute:
 *  
 */
jQuery.extend({ 
    hookExecute: function (function_name){
        //potential security issue
        if (eval ('typeof '+function_name+'=="function"')){
            eval(function_name+'()');
        }else{
            //debug
        }
    }
});

Share it!

It would make more sense to name the function "executeHook". The following is a rewrite that shouldn't have any security issues.
jQuery.extend({
  executeHook: function(hookName) {
    if (typeof window[hookName] == 'function') {
      window[hookName]();
    } else {
      //debug
    }
  }
});