Monday 23 December 2013

How to extend jQuery on() and add custom events.

Note: The code for this can be found in the js-extend library, on GitHub...

https://github.com/johncmolyneux/js-extend



I recently wrote a piece of code to handle what I termed as a custom event.  It was a plugin that would trigger a function when the enter key was pressed in a selected element.  After I'd done that I was curious about turning it into an event that I could assign an event handler to, using jQuery's built-in methods, so I came up with this...

// custom event container
$._customEvents = {};
$.createEvent = function (trigger, notifier) {
    $._customEvents[trigger] = notifier;
};

// extend .on() so custom events can be handled
$.fn._on = $.fn.on;
$.fn.on = function () {
    for (var event in $._customEvents) {
        if (event == arguments[0]) {
            $._customEvents[event](this, arguments[1]);
            return this;  // return the element so we can chain as normal
        }
    }
    return $.fn._on.apply(this, arguments);
};
What that does is extend jQuery's on() function so that you can create your own events that can be attached to elements.  Like this, for example...
// fires when the enter key is pressed within a selected element (must accept keyup)
$.createEvent("enterkey", function (element, callback) {
    var $element = $(element);
    $element.on("keyup", function(e) {
        var code = (e.keyCode ? e.keyCode : e.which);
        if (code == 13) {
            callback();
        }
    });
});
That's the enter key pressed event I mentioned above, but added to the on() function using the new function, createEvent().

Once the above is done then you can use that event wherever you like.  You can attach that to any relevant element and assign an event handler, like this...

$("input").on("enterkey", function() {
    console.log("enter key pressed");
});
As you can see, it's simple to add the event handler code now, just like any of the standard events that are included in jQuery.  This would make it very easy to create custom events that you could use throughout your code, just by having a common javascript file included.  You can obviously create any event you like.

The example above is just one I needed for an application I was working on.  Further custom methods will be added to the source which is available from the GitHub link at the top of this post.


Hopefully this will help others keep code tidy, segregated and easy to understand.

No comments:

Post a Comment