JQuery 3 - Reinventing Events
Written by Ian Elliot   
Monday, 03 April 2017
Article Index
JQuery 3 - Reinventing Events
Bubbling & Capture
Event Data
Bubbling & Delegation

The jQuery event system is very general and it even works with standard JavaScript and DOM objects. For example:

var obj=$({}).on("myevent",function(event,param1,param2){
                               alert(param1 + param2);
               });

obj.trigger("myevent",["first","second"]);

In this case the event handler is attached to the empty object and we trigger the same event on that object. 

Not only will trigger fire event handlers that you have attached to an object it will also attempt to run properties with the correct name as functions. 

If an object has a property that is the same name as the event then it will be run as a method i.e. without any event parameters. 

If an object has a property that has "on" in front of the event name then this will be run as an event handler. That is it will be called with an event object and any custom parameters you might have defined. 

This calling of properties can be useful but it can also cause problems. To avoid calling any properties the might have the same name has an event you can use the triggerHandler function in place of trigger. 

Notice that triggerHandler will not call any methods called event but will call any methods called onevent as event handlers. It also only operates on the first element of any list of matched elements. Also it doesn't bubble events, see later, and it returns the last event handler's result not a jQuery object. 

The main use of custom events is to provided an organized way of passing information about the state of any custom component you might implement. For example, you might implement a custom dataChange event if your component is updated by the user or an outside entity. This would allow a programmer using your component to write code that could react to the change without having to get involved in the internals of your component. Custom events can also be useful in JavaScript libraries that don't implement a UI. For example you could have an event that indicated an error condition or that something was complete in an object that implemented some numerical procedure.

Bubbling  & Delegation

We have already discussed the idea of event bubbling in the context of the DOM. jQuery takes this a little further. You can use the selector part of the on function call to control the way that an event handler behaves during event bubbling.

If you don't specify a selector then you get the classical bubbling behaviour. That is the event handler is attached to each element in the jQuery results. It is fired when an event occurs on that element or bubbles up to that element as a result of an event on a child element. 

To illustrate this we can re-implement the earlier example but using jQuery:

<div id="div1">
Some Text
 <button id="button1">
 Click me
 </button>
</div>

$("#div1").on("click",function(){alert("div");}); $("#button1").on("click",function(){alert("button");});

 

If you click on the button then you will see the button message followed by the div as the event bubbles up. If you click on the div you will only see the div message. 

We can use this to find out about the information about the event passed in the event object:

$("#div1").on("click",function(event){
                 alert($(event.target).attr("id"));}); $("#button1").on("click",function(event){
                 alert($(event.target).attr("id"));});

Now if you click in the button you will see the button1 message twice once from the button's event handler and once from the div's event handler. The target is the button in both cases. 

If you change the code to:

$("#div1").on("click",function(event){
        alert($(event.currentTarget).attr("id"));}); $("#button1").on("click",function(event){
        alert($(event.currentTarget).attr("id"));});

you will see button1 followed div1 as currenTarget gives the element the event handler invoked by the bubbling is attached to.

Notice that you can stop bubbling by calling the event object's stopPropagation or by just returning false.  Notice that this doesn't stop any other event handlers on the same element from running - just the bubbling of the event. If you want to stop everything after the current handler, other event handlers and bubbling, then use stopImmediatePropagation. Notice that this is the only way to stop event handlers on the same element from running. The reason is that the list of handlers to run is constructed when the event occurs and, if you remove an event using off, this does not remove it from the list of event handlers to run. The removal will only have an effect when the event next occurs. 

This is just standard HTML event bubbling implemented by jQuery. If you specify a selector then you get something different. What happens is that if a child element matches the selector then the parent will provide the event handler for the event. This is called a delegated event handler. Notice that, unlike the default bubbling, the child element doesn't have an event handler of its own. 

An example will help make delegation clear:

$("#div1").on("click","button",function(event){
        alert($(event.currentTarget).attr("id"));});

Notice that now we have specified a selector "button". This means that any event that occurs on a button that is contained within the div will be handled by the event handler. Now if you click on the button you will see the button1 message and no div1 message. What might be more surprising is that you don't see anything if you click on the div.

In this case the div's event handler is only handling events on any button objects the div contains. 

This is a particularly useful feature if you plan to dynamically add elements into  the container because the event handler will be called for events on elements that didn't exist when it was attached to the container. 

It is fairly easy to understand how delegation works. When you click on the button it doesn't have an event handler attached so no event handler is called but the event still bubbles up to the div. At this point jQuery intercepts it and check to see if there is a delegated event handler that matches the event and the element that the event occurred on. If so the delegated event handler is called.  

You also need to know that in this case target is button1, currentTarget is the element that the delegated event is handling  i.e. button1 and delegateTarget is the element that the handler is actually attached to i.e. div1.

Also notice that this is the same as target for direct and delegated events.

 

Just jQuery
Events, Async & AJAX

Is now available as a print book: Amazon 

jquery2cover

 

Contents

  1. Events, Async & Ajax (Book Only)
  2. Reinventing Events
  3. Working With Events
  4. Asynchronous Code
  5. Consuming Promises
  6. Using Promises 
  7. WebWorkers
  8. Ajax the Basics - get
  9. Ajax the Basics -  post
  10. Ajax - Advanced Ajax To The Server
  11. Ajax - Advanced Ajax To The Client
  12. Ajax - Advanced Ajax Transports And JSONP
  13. Ajax - Advanced Ajax The jsXHR Object
  14. Ajax - Advanced Ajax Character Coding And Encoding 

Also Available:

buy from Amazon

smallcoverjQuery

 

Advanced Attributes

 

Banner


JavaScript Canvas - Fetch API

Working with lower-level data is very much part of graphics. This extract from Ian Elliot's book on JavaScript Graphics looks at how to use typed arrays to access graphic data.



JavaScript Jems - The Inheritance Tax

JavaScript should not be judged as if it was a poor version of the other popular languages - it isn't a Java or a C++ clone. It does things its own way.  In particular, it doesn't do inheritance  [ ... ]


Other Articles

To be informed about new articles on I Programmer, sign up for our weekly newsletter, subscribe to the RSS feed and follow us on Twitter, Facebook or Linkedin.

espbook

 

Comments




or email your comment to: comments@i-programmer.info



Last Updated ( Thursday, 05 May 2022 )