JavaScript/Notes/IBD: Difference between revisions

From Noisebridge
Jump to navigation Jump to search
Garrett (talk | contribs)
Garrett (talk | contribs)
Line 3: Line 3:
# Event handler properties
# Event handler properties
# DOM event registration mechanisms
# DOM event registration mechanisms
=== Common Interface ===
Each interface shares the following methods:
<source lang="javascript">
<source lang="javascript">
get(src, sEvent); // Gets an event publisher.
get(src, sEvent); // Gets an event publisher.
Line 8: Line 11:
removeCallback(o, type, cb[, useCapture);
removeCallback(o, type, cb[, useCapture);
</source>
</source>
The DOM events interface has a parameter the capturing phase of the Event phase in <code>removeCallback</code>.
DOM events interface also has special methods for working with DOM events, such as <code>getTarget</code>. However, this is a design smell. Those methods could be refactored to be hidden, and a custom adapted Event instance could be passed to the handler, much like jQuery's adapted event.


==== Event Handler Properties ====
==== Event Handler Properties ====

Revision as of 08:25, 1 November 2013

Interface Based Design

Using a common interface, different Event adapters are designed to handle different types of event registration:

  1. Event handler properties
  2. DOM event registration mechanisms

Common Interface

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

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

DOM events interface also has special methods for working with DOM events, such as getTarget. However, this is a design smell. Those methods could be refactored to be hidden, and a custom adapted Event instance could be passed to the handler, much like jQuery's adapted event.

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>