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() methodthat 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
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.
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.
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