Clarification:
I'm only targeting modern browsers that support createEvent, addEventListener, etc....
Question
I mean natively, in JavaScript. A search shows that they are not using createEvent().
I'm looking here in the documentation for answers but did not find any.
I did a search for createEvent() in the source here but there were no hits.
How does backbone implement events from a native language perspective?
Are they using the observer pattern?
If JavaScript already has custom events ( via createEvent() ) available, and event listeners available as well ( addEventListener() why don't they use the built in events?
It doesn't make sense to use native events for anything but a backbone view. Backbone provides event management for models, collections, and generally
Native events (via createEvent, addEventListener) are tied to a DOM node. Models and collections are not associated to a DOM node - you'd have to jump through a lot of unnecessary hoops to reuse that code.
Not really, no. Backbone.Events is a lot closer to the publish-subscribe pattern. An object maintains a list of event listeners for a named event (via on), and then that object triggers a call to those listeners via trigger when it wants to fire an event.
At its core, Backbone maintains an array of event listeners per event (and in older versions of backbone, it used to use a linked list; that was slower). Each object maintains its own list of listeners; there is no central registry.
On trigger, backbone calls all the listeners registered for that event; and it also calls any listeners for the special-cased all event.
Backbone does it like this. It's 163 lines of code counting blanks and comments.
To clarify the how
on|bind, off|unbind, trigger, once, listenTo, stopListeningAs for why, it's based on design decisions that the author and contributors have made that they feel fit the goals and style of the project. The namespacing and multi-event bindings are nice conveniences given common patterns used by backbone models, collections, and views.
Yes, they are using the observer pattern. All event-based systems incorporate an implementation of the observer pattern. Events, pub/sub, and observer are, speaking broadly, synonymous, although some may find it important to distinguish them when talking in detail.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With