This library simplifies the event delegation pattern for DOM events. When you
DOMListener with a DOM node, you can associate event handles with any
of its descendant nodes via CSS selectors.
Say you have the following DOM structure.
Now you can associate a
click event with all
.grandchild nodes as follows:
DOMListener = require 'dom-listener' listener = documentquerySelector'.parent'listeneradd '.grandchild''click' # handle event...
To create a selector-based handler, call
DOMListener::add with a selector,
and event name, and a callback. Handlers with selectors matching a given element
will be invoked in order of selector specificity, just like CSS. In the event
of a specificity tie, more recently added handlers will be invoked first.
listeneradd '.child.foo''click' # handler 1 listeneradd '.child''click' # handler 2 listeneradd '.child''click' # handler 3
In the example above, all handlers match an event on
.child.foo, but handler 1
is the most specific, so it will be invoked first. Handlers 2 and 3 are tied in
specificity, so handler 3 is invoked first since it is more recent.
To create event handlers for specific DOM nodes, pass the node rather than a
selector as the first argument to
childNode = documentquerySelector'.child'listeneradd childNode'click' # handle inline event...
This is a bit different than adding the event handler directly via the native
.addEventListener method, because only inline handlers registered via
DOMListener::add will correctly interleave with selector-based handlers.
Interleaving selector-based handlers with native event listeners isn't possible
without monkey-patching DOM APIs because you can't ask an element what event handlers are registered.
Disposing of Handlers
If you want to remove an event handler, call
.dispose() on the
disposable = listeneradd 'child''click' # handle event disposabledispose # remove event handler
Destroying the Listener
If you want to remove all event handlers associated with the listener and
remove its native event listeners, call
listenerdestroy # All handlers are removed
You can add new event handlers and call
.destroy() again at a later point.