© Russ Ferguson and Keith Cirkel 2017
Russ Ferguson and Keith CirkelJavaScript Recipes10.1007/978-1-4302-6107-0_18

18. Working with Events

Russ Ferguson and Keith Cirkel2
(1)
Ocean, New Jersey, USA
(2)
London, UK
 

How Do Events Work in JavaScript?

Problem

What are DOM events and how do you handle them?

Solution

DOM events notify you when something is happening in the browser, for example a mouse click. There is a long list of events that you as a developer can listen for. A function is then called to handle the event once it occurs.

The Code

function loadedFunction(){
         console.log('The DOM has been loaded')  //returns The DOM has been loaded
}
document.addEventListener('DOMContentLoaded', loadedFunction, false);
Listing 18-1.
Listening for the DOMContentLoaded Event

How It Works

Events are attached to DOM elements and get executed when that type of event happens. This chapter uses the addEventListener method to register events. This method not only provides a way of listening for a certain type of event, but also allows you to register multiple events to the same object.
This method takes three properties —the type of event, which is a string that represents the event (click, DOMContentLoaded, and keypress), the listener, which a function that gets executed when the event type has occurred, and useCapture, which is a Boolean that will tell the browser how to send or propagate the event to other elements that have registered a handler for the same event.

How Do Events Propagate Through a Browser?

Problem

You want to know how nested elements in the browser are alerted when an event occurs.

Solution

JavaScript goes through three phases capturing, target, and bubbling . How the browser responds to these events is determined by the last of three parameters of the addEventListener function.

The Code

function assignListeners(){
        var divs = document.getElementsByTagName('div');
        for(var i = 0; i < divs.length; i++){
             divs[i].addEventListener('click', showID, true);
             divs[i].addEventListener('click', showID, false);
   }
}
function showID(evt){
         alert(evt.currentTarget.id)  
         //returns when clicking on div 3 it will return
         //3,2,1 for the capture phase, then 1,2,3 for the bubbling phase
}
document.addEventListener('DOMContentLoaded', assignListeners, false);
Listing 18-2.
Event Propagation Based on the useCapture Property (the Default Value Is False)

How It Works

Before an event is dispatched to its target, the browser determines what is called the propagation path. This path is the hierarchical tree-like structure of the document.
The first phase is the capture phase, and once the path has been set, the event travels down the path to the target’s parent element. This phase usually starts at the window object.
The second phase is called the target phase. When the event reaches its target, the event can indicate if it should then bubble up to the top. If the preventDefault() method is used, it prevents bubbling from happening and the event stops at this phase.
The third is the bubble phase , where the event reverses order starting with the target’s parent object and goes back up the path to the window. If, in the previous event, the preventDefault() method was executed, bubbling will not occur.
If multiple eventListeners are registered to the same object with the same properties, the duplicate instances are ignored. They do not cause the event to be handled more than once.

How Do You Create Custom Events in JavaScript ?

Problem

You want to create events that are not part of the built-in events that JavaScript uses.

Solution

The Event constructor and the CustomEvent interface allow you to create custom events.

The Code

var myEvent = new Event('finished');
var myOtherEvent = new CustomEvent('done', {'detail': 'done looping!'});
document.addEventListener('finished', function(e){
       console.log('finished event called');
});
document.addEventListener('done', function(e){
       console.log(e.detail);
})
for(var j = 0; j < 100; j++){
       if( j == 99){
                  document.dispatchEvent(myEvent);
                  document.dispatchEvent(myOtherEvent);
       }
}
Listing 18-3.
Dispatching Custom Events

How It Works

Custom events can be created by using either the Event constructor or the CustomEvent interface. The first lets you make an object that can be dispatched when needed and listened by any addEventListener() method. The event object passed to the function resembles an object that came from any other event.
The second method (using the CustomEvent interface) allows you to attach any custom data to the event that you would like and still be able to retrieve the data using a function handler.
In the first example, a custom event called finished is dispatched when the for loop reaches 99. This is then picked up by an event listener that triggers an anonymous function that will write to the console.
The second event called done has two parameters when using the CustomEvent interface—the name of the function and an object with a property called detail. This property will contain any extra information that needs to be passed to the event handler. It is exposed in the same way you would work with other event properties.

How Do You Remove Event Listeners When They Are No Longer Needed?

Problem

You want to remove event listeners when they are no longer necessary.

Solution

The removeEventListener() method removes registered events.

The Code

var textField = document.getElementsByTagName('input');
var isListening = true;
function changeMessage(e){
         if(isListening){
                   isListening = !isListening;
                   document.removeEventListener('click', changeMessage);
                   textField[0].value = 'eventListener = ' + isListening;
         }
}
function setupDoc(e){
         textField[0].value = 'eventListener = true';
         document.addEventListener('click', changeMessage);
}
document.addEventListener('DOMContentLoaded', setupDoc);
Listing 18-4.
Removing Events with removeEventListener

How It Works

When you no longer want an event attached to an object, the removeEventListener() method will remove the event so that when action is taken, the event handler will not react to it. The combination of add and remove event listeners can give you the ability to use events when needed and ignore them when they are not needed.
When removing events, the same arguments must be present. If the method is used and they do not match the arguments of the addEventListener, it will have no effect.
When removing events that use the useCapture argument, each event needs to be removed separately. For example, if an object has been registered twice, one with the capture and the second without, they would need separate removeEventListener calls to remove both events.
In this example, an event listener is added to the document. When the document is clicked it will run the changeMessage function that will change the text in the input field. The if statement inside this function will never become true a second time because the event listener has been removed from the document. If the removeEventListener() method is commented out, then the value of the input field would change on every click of the document.

What Is an Event Emitter in NodeJS ?

Problem

You want to know what event emitters are in NodeJS and how they are similar to what is in the browser.

Solution

Event emitters are similar to addEventListener() in a browser. Objects will broadcast or emit an event and other objects will listen for them.

The Code

//NODEJS CODE
const EventEmitter = require('event');
class EmitterClass extends EventEmitter{}
const emitterInstance = new EmitterClass();
emitterInstance.on('firstEvent', function(){
         console.log('firstEvent fired')
});
function secondEventHandler(data){
         console.log('secondEvent fired with data = ' + data)
}
emitterInstance.addEventListener('secondEvent', secondEventHandler);
emitterInstance.emit('firstEvent');
emitterInstance.emit('secondEvent', 'This is the data from the secondEvent');
emitterInstance.removeEventListener('secondEvent', secondEventHandler);
Listing 18-5.
Sample Code for NodeJS Event Emitters.

How It Works

NodeJS is a JavaScript runtime environment. When most people think of NodeJS, they think of it as a web server. Node uses the Google V8 JavaScript engine to compile JavaScript code to native machine code. Node’s use of modules allows developers to handle functions like networking and cryptography.
In this example, Node is using the Event module. This process is similar to creating custom events in Listing 18-3. The module is assigned a variable called EventEmitter, which is then used to extend a the class EmitterClass.
Like with other JavaScript classes (classes are covered in Chapter 17), you can create an instance of this class. This new instance can now broadcast or emit events and listen for them.
The uses of on and addEventListener provide the same result. You can assign an anonymous function or a named function as the handler.
The emit function is similar to dispatchEvent at this point. The function contains two parameters, the name of the event and optionally any data associated with the event.
The last part of this example adds the removeEventListener method. Just like on the client side, it will remove events, making sure they are not handled in the future.
NodeJS has a long list of methods that can be used with the EventEmitter . Some of these will allow an event to be handled only once; others can set the maximum amount of listeners for an event or remove all listeners for an event.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.128.105