Javascript dispatchEvent - Why is it needed? - javascript

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.

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.

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

Related

Detect event listener from custom element (emitting events lazily)

I am writing a custom element and I want to periodically emit an event.
Emitting the event requires some work, so I was thinking maybe I can be lazy and only emit the event (and do the work) if there is a listener.
Is it possible to detect that someone is listening to an event (non bubbling)?
And in that case start emitting, until the listener is removed.
Or will the Javascript runtime be smart enough to not run the interval (where the only side effect is creating an event) when there is no listener?
With Javascript standard events, it appears you can't (unless you override the registration mechanism).
But with custom registering and callback methods, you can achieve this by implementing the Observer pattern.
Anyway, it you're lazy maybe it's easier to send useless events :-)

Storing data on a DOM Event object

In my use case I have many events occurring at the same time, and each event has different ways of being handled.
Due to event bubbling sometimes it is necessary to ignore specific events (not executing the callback handler) because that event was already handled.
Sometimes you can not simply stop propagation of the event without breaking something else.
For the above reasons I have tried to set a custom flag or data on the event object. For example after it had been handled setting event.handlerExecuted = true. However I found this way of doing it to work inconsistently, and it is basically a hack.
I also want to avoid using global flags or storing references to event objects somewhere..
Some events behave like mousedown -> mouseup -> click each of these "steps" represents a different event, so altering the mousedown event does not guarantee you still have that data available on the click event object.
Is there a proper way of dealing with this problem?

is there any way to instrument javascript event handler firing using javascript?

is there any universal way to instrument javascript event handler firing using javascript?
for example, I want to do something before the event handler firing, so when to fire an event, I would like to execute my code first then the event handler code.
The problem is that there are multiple ways to register event handlers, I would like to handle all of them: html, javascript
No, there's not.
You can hook addEventListener and removeEventListener, which would allow you to intercept both the registration and invocation of event listeners by JS code. However, this will not capture event listeners set in ways such as elt.onclick. Nor of course will it catch listeners set up via the old IE attachEvent API. Most importantly, it will not help with you that events that are generated and listened for internally, such as a mouse click on a check box.
You might be tempted to hook createEvent and dispatchEvent in similar fashion, but that will capture only events that are explicitly created or dispatched in the JS code.

Difference between document.addEventListener and window.addEventListener?

While using PhoneGap, it has some default JavaScript code that uses document.addEventListener, but I have my own code which uses window.addEventListener:
function onBodyLoad(){
document.addEventListener("deviceready", onDeviceReady, false);
document.addEventListener("touchmove", preventBehavior, false);
window.addEventListener('shake', shakeEventDidOccur, false);
}
What is the difference and which is better to use?
The document and window are different objects and they have some different events. Using addEventListener() on them listens to events destined for a different object. You should use the one that actually has the event you are interested in.
For example, there is a "resize" event on the window object that is not on the document object.
For example, the "readystatechange" event is only on the document object.
So basically, you need to know which object receives the event you are interested in and use .addEventListener() on that particular object.
Here's an interesting chart that shows which types of objects create which types of events: https://developer.mozilla.org/en-US/docs/DOM/DOM_event_reference
If you are listening to a propagated event (such as the click event), then you can listen for that event on either the document object or the window object. The only main difference for propagated events is in timing. The event will hit the document object before the window object since it occurs first in the hierarchy, but that difference is usually immaterial so you can pick either. I find it generally better to pick the closest object to the source of the event that meets your needs when handling propagated events. That would suggest that you pick document over window when either will work. But, I'd often move even closer to the source and use document.body or even some closer common parent in the document (if possible).
The window binding refers to a built-in object provided by the browser. It represents the browser window that contains the document. Calling its addEventListener method registers the second argument (callback function) to be called whenever the event described by its first argument occurs.
<p>Some paragraph.</p>
<script>
window.addEventListener("click", () => {
console.log("Test");
});
</script>
Following points should be noted before select window or document to addEventListners
Most of the events are same for window or document but
some events like resize, and other events related to loading,
unloading, and opening/closing should all be set on the window.
Since window has the document it is good practice to use document to
handle (if it can handle) since event will hit document first.
Internet Explorer doesn't respond to many events registered on the
window,so you will need to use document for registering event.
You'll find that in javascript, there are usually many different ways to do the same thing or find the same information. In your example, you are looking for some element that is guaranteed to always exist. window and document both fit the bill (with just a few differences).
From mozilla dev network:
addEventListener() registers a single event listener on a single
target. The event target may be a single element in a document, the
document itself, a window, or an XMLHttpRequest.
So as long as you can count on your "target" always being there, the only difference is what events you're listening for, so just use your favorite.
In my opinion, it is generally better to pick the closest object to the source of the event that meets your needs when handling propagated events.
So, if you want the event to happen to the element, it's better to use window.addEventListener() (assume the window variable is an element) because the most important thing here when listening to an event is that the code and event execution work faster: the only thing that matters in this case.

Backbone.js best practice for event handlers naming

Let's say I have a function in a view that triggers when some kind of state is changed.
What would be best to name it and why?
stateChange
stateChanged
onStateChange
onStateChanged
I personally prefer to use onEventName names keeping the native naming convention for DOM event handlers.
Like myElement.onclick = function() { /* ... */ } for click event.
So for myEvent I'm using a handler named onMyEvent.
And if I have event stateChange, then I'll use onStateChange handler.
But really this question is more specific for each team of developers and code-style conventions inside the team/company.
So the main goal in such kinds of questions is to keep the code style the same in all parts to ensure readability.
Therefore if you're working in a team, just keep sticky to the team's code writing conventions and if you're working alone on existing code, try to keep its code style (sure if that style is not obviously ugly).
UPDATE: Understanding.
What is the event? Roughly it's an action initiated outside or inside the program, in other words, something happens in the system, e.g. some state changes (the state of the keyboard, of the mouse, of I/O devices, etc.) doesn't matter how (the user clicked on mouse or some program sent the mouse click signal to the system).
Say the browser window is subscribed to get notifications about some events and the operating system sends them to it as soon as possible, we'll assume that at the same time when something happens. So if the user clicks his mouse when the browser window is active and the document has a focus, the browser says to the document to fire the click event. And here our onclick handler starting its invocation. In other words, the system says to us that now happens a change of some state. And we're handling this change and not handling a fact saying to us that the state has been changed.
Let's assume that our handler is named onClicked. Since the handler's name saying in past tense we can get a reasonable question: "When clicked, how long ago it happened? How many times it was clicked? Hmm, maybe it's too late to handle this action (or actions?) at all...". So this name tells us that something happened sometime in past.
In contrast when our handler is named onClick it's obvious that click event just fired and fired once and we were notified about it immediately. And we're going to handle the click event - the information saying to us that the state of the mouse changed right now (not mouse clicked, but the event of click).
So the names in the past tense are more appropriate for the cases when we need to check if some state has been changed or not. E.g. if the variable stores the state = 1 we can call the function isStateChanged(); which will compare the value in state variable with the real value at the current moment. And here the past tense is a good choice for naming.
onStateChanged because this function triggers whenever some kind of state is changed.
I Googled a few names and noted the number of results returned. You can get some indication of the relative popularity of the most common forms for event handlers:
stateChanged 168k
stateChange 81k [1]
handleStateChange 61k
onStateChange 59k
onStateChanged 12k
beforeStateChange 2k
[1] Results show stateChange used mostly as the name of an event, not a handler.
Using different event types gives a much stronger recommendation towards the onStateChange form:
change [2]
onChange 2000k
onChanged 85k
handleChange 36k
beforeChange 27k
afterChange 22k
click [2]
onClick 48000k
onClicked 58k
handleClick 50k
beforeClick 8k [3]
onDrag 100k
handleDrag 36k
beforeDrag 32k
afterDrag 4k
onDragged 5k
[2] Too many results unrelated to programming.
[3] Apparently certain Microsoft API's can anticipate when the user is going to click.
My bet is for stateChanged due:
stateChange looks like an order, and looks like it receives a param with the new state.
onStateChange and onStateChanged are more keys for storing the handlers not the name for the handler itself.
IMHO
I usually go for a 2 factor event name. As an app grows in size, you may have more than one object who's state changes or perhaps a controller that can broadcast change events for more than one object and would therefore want to be able to differentiate between then both in code and in your head:
Object1:event
Object2:event
As for which event name, I think it comes down to personal preference and consistency.
I think one should make a difference based on the actual moment when the action is happening. For me onStateChange means that it is currently changing and I can be notified about this technically speaking right before the change.
OnStateChanged means the action already happened and I am notified at the end of it.
So, in between onStateChange and onStateChanged there is an important intention difference.
First one says "prepare yourself for this change" while the second one says "it's already happened".
Edit: I got carried away by the intention and didn't realize the naming itself.
Why the on prefix? This is reserved for handlers. The handlers will do something related to (on) that event.
So I would go with stateChange and stateChanged.

Categories

Resources