JavaScript/Notes/IBD

From Noisebridge
Jump to navigation Jump to search

Interface Based Design

Using a common interface, different Event registries handle different types of event registration:

  1. Event handler properties
  2. Event callback registration methods

DOM Events

DOM events need an adapter for addressing the great difference in old IE's event model, with attachEvent and getting an event's target.

Custom Events

Custom Events are user defined so do not need any adapter.

Encapsulate the Parts that Vary

Event handler properties are useful for custom events and DOM events.

For DOM compatibility, it is often necessary to have methods that will handle old IE event model as well as delegate listeners (See: DOM Event Flow).

Common Interface

Each interface shares the following methods: <source lang="javascript"> // Static: get(src, sEvent); // Gets an event publisher. addCallback(src, sEvent, callback); removeCallback(o, type, cb[, useCapture);

// Instance: eventPublisher.addCallback(sEvent, callback); eventPublisher.removeCallback(sEvent, callback]); </source>

The DOM events interface has an additional parameter the capturing phase of the Event phase in removeCallback.

Event Handler Properties

Each event is a property name. The value is a function or null. The pattern works equally well for custom events on user-defined objects and DOM events.

DOM Elements <source lang="javascript"> el["onclick"] = function(ev) {

 alert(this);

};</source>

Custom Objects and Events <source lang="javascript"> userPicker.onuserselected = function(ev) {

 console.log(ev.user + " chosen.");

}; </source>

Event Listener Interface

<source lang="javascript"> el.addEventListener("click", function(ev) {

 alert("clicked");

}, false); </source>

Custom objects <source lang="javascript"> userPicker.addCallback("onuserselected", function(ev) {

 console.log(ev.user + " chosen.");

}); </source>