Is an Observer pattern useful in JS? - javascript

I've read some articles about the Observer design pattern in JavaScript, but I don't get it: it seems to me quite useless since JS has events. Am I missing something?

Reacting to events like click, resize etc is one thing but limited to the DOM events. However without going into details here, if you look at a library like RxJS (which uses the Observer pattern) you will be able to build powerful Reactive systems, where essentially anything could be treated like events, which in addition to the standard event system, they can be composed, mapped, etc

Related

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

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.

Javascript implementation of Event Aggregator pattern

So I have done a lot of research and for some reason I can't find an implementation of the Event Aggregator pattern in Javascript. In fact, the only language that's always used is C# and there's always generics being used. It's a very useful pattern so I fail to realize why it only seems to be 'meant' for .NET. I was hoping that someone would be able to provide an implementation in Javascript or at the very least Java and NOT C# (I've seen enough of that). Thank you!
How to:
Get one on the many general purpose publish/subscribe libraries that are implemented and ready to use. ie https://github.com/mroderick/PubSubJS (or roll your own - it ain't that hard)
Instantiate your event source objects, implement publishing of events.
Instantiate your aggregator, make it subscribe to your source objects, and offer publishing of received events.
Instantiate your target objects, make them subscribe to your aggregator.
In Javascript the Event Aggregator pattern does not need its own implementation. It is just an object that subscribes to multiple publishers and also publishes to multiple subscribers.
Since there are no type checking or interfaces anything of that sort, you dont need the pattern implemented before you use it, it is just a trivial exercise in pub/sub, which is probably why you can't find it anywhere as an "abstract" implementation.
Look into redux if you want to see something reusable that solves problems in the same domain as the event aggregator pattern, but offers a lot more.

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.

Does Functional Reactive Programming in JavaScript cause bigger problems with listener references?

In JavaScript the observer pattern is used quite often. There is one tricky thing with it and that's the references the subject keeps of the observers. They require cleanup. For regular applications I use the following rules of thumb:
If the subject has a life span shorter than (or equal to) the observer, I can just do subject.on('event', ...)
If the subject has a life span longer than the observer, I need to use observer.listenTo(subject, 'event', ...)
In the second case, the listenTo is aware of the life-cycle of the observer and it will automatically remove the listeners when it's time for the observer to die.
In modern day SPA (Single Page Application) style, where only parts of the application are active at any time this is something that becomes very important. If you combine that with web sockets, which are a perfect candidate for an event stream and most likely long lived, this becomes even more important.
With FRP, having something like an event stream representing changing values over time, I am (without knowing it) creating a lot of listeners. Each filter, map and flatMap creates a new stream that is tied (probably using a listener) to the previous one.
In my mind it seems quite tricky to determine how and when I need to remove those listeners. I can not imagine me being the first to think about this problem, yet I could not find much about this on the Internet.
I have seen some frameworks in other languages use weak references. JavaScript does not have the concept of weak references (WeakMap is not usable here). Even if it had though, it seems like a bad idea because it's unclear when garbage collection takes place.
How is this solved in the current frameworks?
Do the frameworks tie into the life-cycle of objects? If yes: how?
In RxJs, each Observer will, by default, have a separate listener on the original event source. So, if you have
var s = $('#textInput').keyupAsObservable()
s.subscribe(subscriber1);
s.map(function() {}).subscribe(subscriber2);
You'll have two keyup listeners. You can use .publish().refCount() to make an Observable maintain a single connection to its source.
In Bacon.js, Observables always maintain a single connection to their source.
In both libraries the connection to the source is created lazily (when an Observer is added) and removed automatically when the (last) Observer is removed. Therefore you don't have to manually manage the listeners.
However, in the case where the subject has a longer life span than the Observer, you'll have to make sure the observer stops its subscription when its lifespan ends, or you'll have a leak. Neither libraries have any "magical" way of managing this, because to the library, your Observer is just a function.
Personally I often create an Observable called death or whatever to signal the end-of-life for the Observer and then instead of subscribing to the subject I subscribe to subject.takeUntil(death).
Regarding Elm, my understanding is that you have set up your entire event network at once, so there's no possibility for leak; Observers cannot be added at a later stage.

What is the difference between different ways of Custom event handling in JavaScript?

I came across the below posts about custom event handling in JavaScript. From these articles, there are two ways (at least) of handling/firing custom events:
Using DOM methods (createEvent, dispatchEvent)
How do I create a custom event class in Javascript?
http://the.unwashedmeme.com/blog/2004/10/04/custom-javascript-events/
Custom code
http://www.nczonline.net/blog/2010/03/09/custom-events-in-javascript/
http://www.geekdaily.net/2008/04/02/javascript-defining-and-using-custom-events/
But what is the recommended way of handling (firing & subscribing) custom events?
[Edit] The context for this question is not using any libraries like jQuery, YUI,... but just plain JavaScript
[Edit 2] There seems to be a subtle differences, at least with the error handling.
Dean Edwards ( http://dean.edwards.name/weblog/2009/03/callbacks-vs-events/ ) is recommending the former way for custom event handling. Can we say this a difference?
What your describing is the difference between
A custom event based message passing system
manually firing DOM events.
The former is a way to use events for message passing. An example would be creating an EventEmitter
The latter is simply a way to use the browsers build in DOM event system manually. This is basically using the DOM 3 Event API which natively exists in (competent / modern) browsers.
So the question is simply what do you want to do? Fire DOM events or use events for message passing?
Benchmark showing DOM 3 custom events is 98% slower
The DOM appears to have a huge overhead. It does so because it supports event propagation and bubbling. It does because it supports binding events to a DOMElement.
If you do not need any of the features of DOM3 events then use a pub/sub library of choice.
[Edit 2]
That's all about error handling, how you do error handling is upto you. If you know your event emitter is synchronous then that's intended behaviour. Either do your own error handling or use setTimeout to make it asynchronous.
Be wary that if you've made it asynchronous you "lose" the guarantee that the event handlers have done their logic after the emit/trigger/dispatch call returns. This requires a completely different high level design then the assumption that event emitters are synchronous. This is not a choice to make lightly
There are pros and cons to each. Use what suits you.
The most obvious "con" to using the DOM methods is that they're tied to browser-based deployments and involve the DOM in things even if it doesn't really make sense (e.g., the messaging isn't related to DOM objects), whereas a standard Observer-style implementation can be used in any environment, not just web browsers, and with any generic object you like.
The most obvious "con" to doing your own Observer implementation is that you've done your own Observer implementation, rather than reusing something already present (tested, debugged, optimised, etc.) in the environment.
Many libraries already provide a way to deal with events, and I would recommend on just using an existing library. If you use the DOM, you are assuming that the browser provides the necessary support, whereas if you use a custom mechanism, you might be sacrificing speed for the custom implementation. If you rely on an existing library, the library can choose the appropriate tradeoffs.
For example, Closure provides EventTarget which has an interface simliar to that of the DOM mechanism, but which does not depend on the browser to provide native support for it.

Categories

Resources