*When or why* would you use JavaScript's EventTarget? - javascript

I originally was reading this:
https://developer.mozilla.org/en-US/docs/Web/API/EventTarget
But, then I came upon this question here:
How to use JavaScript EventTarget?
However, when or why would a developer need to use EventTarget?
I'm still learning. I know the SO community doesn't like duplicate questions, but I feel this isn't since it's asking a different question than the one I cited above (it only discusses how to use it).

For the same reason you might use EventEmitter in node.js: you have some custom class/object which you would like to emit events.
Events are useful to allow your object to notify other parts of your code that something interesting has happened, without the object actually knowing anything about the code that uses it.
For example, a link on a page (implemented by the browser as an HTMLAnchorElement object) does not need to know what your code does in response to clicks; you simply register a click event handler (by calling EventTarget#addEventListener('click', …)) and when clicks happen, the browser internally calls EventTarget#dispatchEvent(new Event('click')) and your code handles the event.
Your own custom objects can use this pattern for a wide range of things. Perhaps you'd like to notify things that your object's data has changed -- either as a result of the user doing something or a fetch call returning.
This allows you to build code that is easily composable and testable: the emitter doesn't care who is listening or what that code does, and the consumers don't care about the implementation details of the event getting fired.

Related

What is a good use case for the "all" event ...?

in Backbone.
http://backbonejs.org/#Events-on
I have a single event bus with no namespacing. I don't understand why you would need to use "all".
The example used in the notes is for a proxy but I don't understand why you would want to do this.
You can come up with different use cases, for example:
Logging all changes that happen on the object
Using it as Adapter from one framework to the other
Wrapping original object in proxy object, and triggering events through it
e t.c.
It's up to you, if you need to use it or not, it's just there, with no obligations.
I use this to let the user "something" is going on. As a programmer I am also aware that Backbone is firing events.
You can use a subtle animation that shows the page is firing events.
It is also a good way to give a top level view of how your application is working.

Access ReactJS's internal event mapping

Since ReactJS uses event delegation, is there a way to access the internal node/events mapping?
It doesn't have to be pretty, wrapping one of the responsible functions (like the equivalent of jQuery's on()) and doing custom housekeeping would work fine and would actually be preferable to accessing that data through an object of some sort.
If I could get the selector, event and handler (optional) that'd be great, as I'm already doing this for jQuery.
The reason I'm asking is because I'm trying to optimize Arachni for ReactJS applications and having prior knowledge of which elements actually have event handlers (and what they are) would result in a much more efficient scan.
In addition, that data would be of great value when scanning web applications for non security reason's as well, you could gather some very interesting stats that way.

Backbone.Radio: what's the advantage of commands and requests over events

It seems like Backbone.Radio provides 2 new abstractions - commands and requests. They're pretty much identical to Backbone.Events, except that they can have only 1 subscriber. Is that it, and if so what advantage do they provide over events?
I plan on using Backbone.Events/Radio with React.js, if that helps.
I have not actually used Backbone.Radio but do make extensive use of Backbone.wreqr https://github.com/marionettejs/backbone.wreqr which provides an almost identical command service.
In my usage the difference between events and commands is:
For events to work the sender and receiver of an event must both exist and have a reference to each other and the receiver must be in a position to deal with the event properly. This can often be problematic in a fully asynchronous browser environment where different parts of your application are running at the same time.
Commands allow you to decouple the sender and receiver. One object, lets say a View A, can simply send command 'update_user_details'.
My second Object View B sets up a command handler for 'update_user_details' which will change the user details on the screen.
But what if View B does not yet exist, or is not yet rendered. In the event listener pattern you would have to make sure View A exists, that it passes a reference to itself to View B and then you attach an event listener in View B.
With commands it is not a problem, View A sends a command, if no-one has set a handler then nothing bad happens, the command just does nothing.
When View B turns up, totally independent of View A, it sets a handler and will respond to all future commands.
Just a final note about intent:
The event pattern can be thought about in this way: I, View A have just done something, anyone that is interested (the event listeners) can do what they like about it, I View A don't care what you do.
In the command pattern: I View A want someone to do something, I don't care who does it, I just want it done right.
Channels. The key difference with Backbone.Radio over plain vanilla Backbone.Events that I have seen is that it allows you to setup channels to which your code can 'tune in' e.g. from the documentation:
var userChannel = Backbone.Radio.channel('user');
This means that logical functions or apps in your code can emit and handle events only on a specific channel - even if you emit events with the same name, if they're on different channels you won't get cross-contamination. This ties in nicely with the principles behind separation of duties in your code.
The other other difference, and IMHO it's subtle, more to do with elegance of coding than any real functionality difference, is that if you're telling something to respond to an event then it's really a Command, and Backbone.Radio allows you to separate these kinds of event into that type. Similar logic applies to the Requests type.
For completeness...
The docs also explain that a Channel is an object that has all three types of messages (Events, Commands and Requests) mixed in. You mix it into an object (I use Marionette so I'm mixing into an instance of Marionette.Object) using Underscore/Lo-Dash's .extend():
_.extend(objectToBeExtended, Backbone.Radio.Requests);
And the same for Commands of course. The syntax for events is different as that's baked into Backbone itself so the second parameter is just Backbone.Events.

Theory for attaching javascript eventlistener to variables?

I was wondering wether there is a way to attach eventlisteners to variables. The idea is to do something like this:
someVar.addEventListener('change', someTodo, false);
So once someVar is changed by i.e. someVar=1, someTodo would be executed.
I think to understand that - in theory - eventlisteners can be added to everything in the DOM, the problem beeing that variables do not trigger those events, while HTML objects DO trigger them.
If that is indeed correct, the extended question would be: How to train DOM objects to trigger events? I have read something about prototyping, is that the trick here?
Please note: I like to understand and write all of my code myself. So I'd rather be interested in the theory then using some existing thing like jQuery, where all sorts of miracles are baked right in.
Marco
The safe and time tested approach is to use getters and setters on your objects (ie, you only allow access to the variable through object methods like getX()/setX()). You could then have overload setX() to trigger callbacks. There are some languages like Lua and Python where access to an object's members can be caught with meta functions but I do not believe Javascript supports this in any way.

Is it possible enumerate all the page ready event observers, using jquery / js?

Is it possible to report all the observers of the 'ready' events. I have a page where something is happening twice, and i'm trying to chase it back to the source.
Unfortunately you can't do this after it's executed, as it's a special event handler, which that "duplicate" question doesn't really cover.
$(document).ready(func) (or $(func)) or stores the functions you want to call in readyList (internal array). Unfortunately for your situation, but good for performance/garbage collection, this list is nulled out after it runs, so you can't get the list you're looking for.
You can see how this happens in jQuery core here.
Your best bet would be console.log() in a few functions /files to see if you get any duplicates I'd say.

Categories

Resources