Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript dispatchEvent - Why is it needed?

I have code which is written:

window.addEventListener("orientationchange", function() {
    //code here;
}, false);

And it works fine...but I am being told to add by the Mozilla dev page:

elem.dispatchEvent(event);

Can anyone tell me why I need to add the dispatch and why it is working without it (what the dispatch actually does would also be very useful!).

W3C also recommends in the specification to remove an event when done with it, but for an orientation change it could happen at any time, is it OK to leave it there?

Much obliged for any help.

like image 848
user1360809 Avatar asked Dec 26 '22 15:12

user1360809


2 Answers

addEventListener says that, on the object (window in your example) you want to react whenever that object dispatches and event with the a given type (e. g. orientationchange)

You are listening to an event from an object.

dispatchEvent is what you call if you want to send or trigger an event. Internally, the browser is doing this whenever the user rotates their device, which triggers orientationchange . In this specific example, you don't need to trigger this manually unless you need to do so for testing.

removeEventListener does what you'd expect, and makes it so that you no longer are listening for triggered events. It is usually good to do this if you know you no longer want to listen to the event or that the event will no longer be fired so that you can free up memory resources. For your case, it seems like you don't need to do this.

Here is more information about DOM and JavaScript Events, http://www.w3schools.com/jsref/dom_obj_event.asp.

like image 173
lemieuxster Avatar answered Dec 28 '22 05:12

lemieuxster


dispatch meaning send off to a destination or for a purpose.

dispatchEvent is the last step of the create-init-dispatch process, which is used for dispatching events into the implementation's event model.

EventTarget.dispatchEvent

Dispatches an Event at the specified EventTarget, invoking the affected EventListeners in the appropriate order. The normal event processing rules (including the capturing and optional bubbling phase) apply to events dispatched manually with dispatchEvent()

like image 38
Simpal Kumar Avatar answered Dec 28 '22 05:12

Simpal Kumar