Javascript function hooks

EDIT: OK, I believe the following solutions are valid:

  1. Use the jQuery AOP plugin. It basically wraps the old function together with the hook into a function sandwich and reassigns it to the old function name. This causes nesting of functions with each new added hook.
    If jQuery is not usable for you, just pillage the source code, there did not seem to be any jQuery dependencies in the plugin, and the source is simple and very small.

  2. Have an object describing all hooks and their targets and one to store the initial unmodified function. When adding a new hook, the wrapping would be redone around the original function, instead of re-wrap the the previous wrapping function.
    You escape nested functions, and get two objects to handle instead. Potentially, this could also mean easier hook handling, if you add/remove hooks often and out of order.

I'll go with the first, since it's already done, and I don't have performance to worry about. And since the original functions are not affected, even if I switch hooking methods, I'll only need to redo the hook adding, which might be just some simple search&replace operations.


Is it possible to create a mechanism, in which function A might have a set of hooks(functions that will execute before/after function A)?

Ideally, function A would not be aware of hooking functionality, so that I do not have to modify the source code of function A to call the hooks. Something like:

A = function(){
    alert("I'm a naive function");
B = function(){
    alert("I'm having a piggyback ride on function A!"+
          "And the fool doesn't even know it!");
addHook(B, A)//add hook B to function A
//getting alerts "I'm a naive function"/"I'm having a 
//piggyback ride on function A! And the fool doesn't even know it!"

I've been trying to hack something up for a couple of hours, but so far no luck.



Take a look at jQuery's AOP plugin. In general, google "javascript aspect oriented programming".


Might not be pretty but it seems to work...


function A(x) { alert(x); return x; }
function B() { alert(123); }

function addHook(functionB, functionA, parent)
    if (typeof parent == 'undefined')
        parent = window;

    for (var i in parent)
        if (parent[i] === functionA)
            parent[i] = function()
                return functionA.apply(this, arguments)


addHook(B, A);



Very simple answer:

function someFunction() { alert("Bar!") }
var placeholder=someFunction;
someFunction=function() {

This answer is not definitive, but rather demonstrative of a different technique than those offered thus far. This leverages the fact that a function in Javascript is a first-class object, and as such, a) you can pass it as a value to another function and b) you can add properties to it. Combine these traits with function's built-in "call" (or "apply") methods, and you have yourself a start toward a solution.

var function_itself = function() {
    alert('in function itself');
function_itself.PRE_PROCESS = function() {
    alert('in pre_process');
function_itself.POST_PROCESS = function() {
    alert('in post_process');

var function_processor = function(func) {
    if (func.PRE_PROCESS) {;
    if (func.POST_PROCESS) {;

The following function will give you before and after hooks that can be stacked. So if you have a number of potential functions that need to run before the given function or after the given function then this would be a working solution. This solution does not require jQuery and uses native array methods (no shims required). It should also be context sensitive so if you are calling the original function with a context if should run each before and after function likewise.

// usage: 
function test(x) {

var htest = hookable(test);

htest.addHook("before", function (x) {
    alert("Before " + x);
htest.addHook("after", function (x) {
    alert("After " + x);

htest("test") // => Before test ... test ... After test
function hookable(fn) {
    var ifn = fn,
        hooks = {
            before : [],
            after : []

    function hookableFunction() {
        var args = [], 0),
            i = 0,
        for (i = 0; !!hooks.before[i]; i += 1) {
            fn = hooks.before[i];
            fn.apply(this, args);
        ifn.apply(this, arguments);
        for (i = 0; !!hooks.after[i]; i++) {
            fn = hooks.after[i];
            fn.apply(this, args);

    hookableFunction.addHook = function (type, fn) {
        if (hooks[type] instanceof Array) {
        } else {
            throw (function () {
                var e = new Error("Invalid hook type");
                e.expected = Object.keys(hooks);
       = type;
                return e;

    return hookableFunction;

Here's what I did, might be useful in other applications like this:

//Setup a hooking object
    //default hooks (also sets the object)

//Add a hook

//Apply each Hook (can be done with for)

I don't know if this will be useful. You do need to modify the original function but only once and you don't need to keep editing it for firing hooks


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.