jQuery 1.7 Custom Events Using .on Method

The browser event model can behave differently in different browsers. jQuery provides a consistent framework to handle standard events like the mouse click in browsers with an easy to understand syntax. However we are not limited to the set of events provided by jQuery. jQuery provides support for custom events as well.

Custom events provide a great way to decouple your application code and architect new libraries, similar to how we create our own jQuery plugins. You can use them to handle custom scenarios in your application like mail_sent or implement a pattern like the Obeserver pattern (publish-subscribe).

Till version 1.6, jQuery lets you register handlers for custom events using the bind() function and you can fire these custom events using the trigger() function. With jQuery 1.7, you can now use the .on() method that provides all functionality required for attaching event handlers. It’s similar to bind() except that you can now bind multiple events at once, and select a set of children that actually trigger this event.

Let us see a simple example of using the new .on() method to register custom events in jQuery 1.7

<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
    <title>DevCurry.com - jQuery Custom Events</title>
    <script src="http://code.jquery.com/jquery-latest.js"></script>
    <script type="text/javascript">
        $(function () {
            $('#myDiv').on('myEvent', function (e, somesampledata) {
                // write custom code
                $(this).text('Custom Event Triggered. ' + somesampledata);
            });

            $("button").click(function () {
                $("#myDiv").trigger("myEvent", "somedata");
            })
        });
    </script>
    
</head>
<body>
<div id="myDiv">This is a Div with an Attached Custom Event</div>
<button>Trigger custom event</button>
</body>
</html>

As you can see, the on() method listens for events and the trigger() method notifies listeners that an event just occurred. Trigger() method takes two arguments, the event name and an extra optional parameter, if you want to pass any data to the custom event handlers. In our case, we are passing “somedata” to the event handler.

Run the application, click the button and you get this.

image


If you are curious, in jQuery 1.6 you would use bind() to do the same thing . The syntax remains the same, bind() gets replaced with .on(). Here’s the same code without passing an optional param to the trigger() method.

jQuery Custom Events

Note: Just like browser native events, custom events also propagate the DOM Tree
To remove events bound with .on(), use the .off() method. To attach an event that runs only once and then removes itself, use the .one() method.

You may also want to read Create a Custom jQuery Selector

See a Live Demo




About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal.

2 comments:

jQuery Developer said...

Suprotim, this is awesome! I never really think to use events other than click, but I can see how this would be extremely useful. It is the first that I have heard about the jQuery event .one(). Very, Very useful. Thanks

Suprotim Agarwal said...

Glad you liked the post. Make sure you do not get confused between .on and .one. The names are confusing!