Skip to Content
JavaScript: The Good Parts
book

JavaScript: The Good Parts

by Douglas Crockford
May 2008
Intermediate to advanced
172 pages
4h 54m
English
O'Reilly Media, Inc.
Content preview from JavaScript: The Good Parts

Parts

We can compose objects out of sets of parts. For example, we can make a function that can add simple event processing features to any object. It adds an on method, a fire method, and a private event registry:

var eventuality = function (that) { var registry = {}; that.fire = function (event) { // Fire an event on an object. The event can be either // a string containing the name of the event or an // object containing a type property containing the // name of the event. Handlers registered by the 'on' // method that match the event name will be invoked. var array, func, handler, i, type = typeof event === 'string' ? event : event.type; // If an array of handlers exist for this event, then // loop through it and execute the handlers in order. if (registry.hasOwnProperty(type)) { array = registry[type]; for (i = 0; i < array.length; i += 1) { handler = array[i]; // A handler record contains a method and an optional // array of parameters. If the method is a name, look // up the function. func = handler.method; if (typeof func === 'string') { func = this[func]; } // Invoke a handler. If the record contained // parameters, then pass them. Otherwise, pass the // event object. func.apply(this, handler.parameters || [event]); } } return this; }; that.on = function (type, method, parameters) { // Register an event. Make a handler record. Put it // in a handler array, making one if it doesn't yet // exist for this type. var handler = { method: method, parameters: parameters }; if (registry.hasOwnProperty(type)) ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Modern JavaScript for the Impatient

Modern JavaScript for the Impatient

Cay S. Horstmann
Head First JavaScript Programming

Head First JavaScript Programming

Eric T. Freeman, Elisabeth Robson
Learn JavaScript

Learn JavaScript

Shaun Wassell

Publisher Resources

ISBN: 9780596517748Supplemental ContentCatalog PageErrata