Skip to content
chemerisuk edited this page Nov 26, 2014 · 13 revisions

In better-dom event listeners are different. There is no event object passed as the first argument. Also events a low level. In other words the library just uses native methods behind the scenes. It helps your code to be compatable with any other library or a framework.

Registering event listeners

Use $Element#on or $Element#once to attach a listener for a particular DOM event. The second method removes the listener after the first event.

list.on("click", function() {
  // handle event for any element inside
});

If you need to listen to event on a particular element add optional selector to filter bubbled inner events:

lint.on("click", "li", function() {
  // handle event for `li` elements
});

Event handler arguments

Since better-dom doesn't provide direct access to the event object, $Element#on or $Element#once accept extra argument args that you can use to grab the attributes. Some of them have extra hooks or bug fixes:

lint.on("mousedown", ["target", "button"], function(target, button) {
  // NOTE: target is a DOM object!
  target.addClass("selected");
  // the value of button variable is correct in IE8
  console.log(button); // => 0 or 1 or 2
});

You can send extra data for any event using $Element#fire:

DOM.fire("custom:event", 123, "hey");

Those arguments can be accessed via numeric values in the args array (starting from 1!):

DOM.on("custom:event", [1, 2], function(a, b) {
    console.log(a); // => 123
    console.log(b); // => "hey"
});

Also, they are passed into an event handler by default, so you can skip the array argument for the example above:

DOM.on("custom:event", function(a, b) {
    console.log(a); // => 123
    console.log(b); // => "hey"
});

Invoking event methods

For getting access to methods like preventDefault or stopPropagation just use appropriate keys:

link.on("click", ["preventDefault"], function(cancel) {
    cancel(); // prevents default action
});

link.on("click", ["stopPropagation"], function(stop) {
    stop(); // stops bubbling
});

For preventing default you can also just return false shortcut (it does not stop bubbling):

link.on("click", function() {
    return false; // prevents default action
});

See also

Improved currentTarget