borrame.com - Colección particular de recortes de código y documentación para programación web

Lo más fresco

  1. LPAD en SQL Server Nuevo
  2. Eliminar todos los objetos en SQL Server Modificado
  3. Dominio principal Nuevo
  4. Eliminar formato en Excel Nuevo

Sugerencias del chef

Lo más visitado

  1. Dar formato a un número
  2. Campo autonumérico
  3. Fecha y hora
  4. Cookies
  5. Convertir IP entre cadena y número

Eventos

Hay una infinidad de maneras de asignar eventos a los elementos de una página web:

Clásica
Código: <body onload="foo()">
Inconvenientes: obliga a modificar el HTML de toooooodas las páginas y toooooodos los elementos donde queremos usar el script. Añadir varios eventos al mismo objeto es un desmadre.
Modernista
Código: window.onload=foo
Inconvenientes: al añadir un evento machacamos todos los anteriores.
Utópica
Código: addEventListener() y attachEvent()
Inconvenientes: cada navegador los implementa a su manera, o de ninguna en absoluto.
Geek
Código: addEvent()
Inconvenientes: falla en algunos navegadores y provoca efectos colaterales difíciles de apreciar a primera vista.

¿La solución?

Dean Edwards nos propone el siguiente código casero (sólo he agregado los comentarios en español):

/*
 * Gestión de eventos
 * - http://dean.edwards.name/weblog/2005/10/add-event/
 * - http://dean.edwards.name/weblog/2005/10/add-event2/
 */


/*
 * Ejemplo:
 *
 * function foo(){
 *     alert('La página ha terminado de cargar');
 * }
 * addEvent(window, 'load', foo);
 *
 */

function addEvent(element, type, handler) { // v2005-12-06
    // assign each event handler a unique ID
    if (!handler.$$guid) handler.$$guid = addEvent.guid++;
    // create a hash table of event types for the element
    if (!element.events) element.events = {};
    // create a hash table of event handlers for each element/event pair
    var handlers = element.events[type];
    if (!handlers) {
        handlers = element.events[type] = {};
        // store the existing event handler (if there is one)
        if (element["on" + type]) {
            handlers[0] = element["on" + type];
        }
    }
    // store the event handler in the hash table
    handlers[handler.$$guid] = handler;
    // assign a global event handler to do all the work
    element["on" + type] = handleEvent;
};
// a counter used to create unique IDs
addEvent.guid = 1;

/*
 * Ejemplo: removeEvent(window, 'load', foo);
 */

function removeEvent(element, type, handler) { // v2005-12-06
    // delete the event handler from the hash table
    if (element.events && element.events[type]) {
        delete element.events[type][handler.$$guid];
    }
};


/*
 * Funciones privadas (son utilizadas por las dos anteriores)
 */

function handleEvent(event) { // v2005-12-06
    var returnValue = true;
    // grab the event object (IE uses a global event object)
    event = event || fixEvent(window.event);
    // get a reference to the hash table of event handlers
    var handlers = this.events[event.type];
    // execute each event handler
    for (var i in handlers) {
        this.$$handleEvent = handlers[i];
        if (this.$$handleEvent(event) === false) {
            returnValue = false;
        }
    }
    return returnValue;
};
function fixEvent(event) { // v2005-12-06
    // add W3C standard event methods
    event.preventDefault = fixEvent.preventDefault;
    event.stopPropagation = fixEvent.stopPropagation;
    return event;
};
fixEvent.preventDefault = function() { // v2005-12-06
    this.returnValue = false;
};
fixEvent.stopPropagation = function() { // v2005-12-06
    this.cancelBubble = true;
};

Según nos explica el autor (hay más) funciona en miles de navegadores y no encoge la ropa.

¿Qué eventos podemos manejar?

Un laborioso programador holandés llamado Peter-Paul Koch ha recopiado una lista de eventos en los navegadores más populares. El mismo sitio web contiene información sobre el tema para tomar y dejar.

Esta página ha sido impresa el miércoles 10 de marzo de 2010 (22:18:20 +0100) desde http://borrame.com/recortes/javascript/eventos.html. La última vez que miré contenía HTML válido con CSS fresquito y si tiene flatas de ortografía ha sido sin querer.

borrame.com es el sitio anteriormente conocido como bits.demogracia.com (no confundir con Demogracia, que sólo pasaba por ahí).

© 2005-2010 by Álvaro G. Vicario (alvaro.es) • Burgos (España) • borrame.com