Sometimes when working with JavaScript libraries and widgets, you may want to extend or augment the behavior of certain functions without breaking the existing functionality or completely extending the object. Todays article will explore the Function Hijacking Pattern, which can be used to augment a function with your own logic.

How to do it…

The following is a simple example using the hijack pattern to augment a function:

How it works …

The is no fancy magic at work here, this pattern simply takes an existing function reference and maps it to a new reference. The original function is then overwritten with one that is more useful, which does something new before executing the original function. In the general example, a simple add that takes two parameters and adds them, is replaced by a new function that can take an optional third parameter.

The hijack of the YAHOO.util.Event.on function is a bit more complicated. As it requires an extra variable, __mouseMoveCallbacks, to store the event callback objects. Additionally, the hijacking function has to parse some arguments so the event handler and callbacks behave the same way they would if executed by YUI. Lastly, as it is written, there is no way to remove these listeners. The YAHOO.util.Event.removeListener function would also need to be hijacked to remove the callback function from the __mouseMoveCallbacks array.

The Y.Widget.initializer function hijack is something useful, if following the coding pattern, where all id attributes inside of the widget, use the widget id as a prefix. Meaning, if the widget id is myWidget, then a button inside the widget would have an id like myWidget_myButton. During the initializer function the id of the boundingBox is stored as _idPrefix. This allows the shortcut method getWidgetNode to return elements by only needing the second part of the id, so getWidgetNode("myButton") would return the button instance. This is a pattern we use at Mint.com to simplify complex id namespaces.

Theres more…

This pattern should be used sparingly, and only with functions that you do not really have control over, such as those created by including a JavaScript library. When possible, it is always better to extend an object with your own class, instead of using this pattern. However, this pattern does provide you with a simple way to add minor changes to existing object functions.