Javascript: gestire gli eventi | MrX

« Arte senza confini e limiti | Main | KNOL: guadagnare conoscendo »

Javascript: gestire gli eventi

By Merlinox | July 23, 2008

Oggi ho trovato un interessante articolo su e sulla gestione degli eventi. Uno script che secondo l’autore è un po’ datato, ma che pare sia ancora attualissimo.

Non vengono usati prototype, jQuery o altri framework . Solamente un paio di funzioni: addEvent, removeEvent.

function addEvent(obj, type, fn){
if (obj.attachEvent) {
obj[’e’ + type + fn] = fn;
obj[type + fn] = function(){
obj[’e’ + type + fn](window.event);
}
obj.attachEvent(’on’ + type, obj[type + fn]);
}
else
obj.addEventListener(type, fn, false);
}

function removeEvent(obj, type, fn){
if (obj.detachEvent) {
obj.detachEvent(’on’ + type, obj[type + fn]);
obj[type + fn] = null;
}
else
obj.removeEventListener(type, fn, false);
}

Utilizzare le due funzioni è veramente molto semplice:

addEvent(document.getElementById('my_elem'),'click',foo);

Con la chiamata di addEvent, l’elemento "my_elem" avrà un evento legato al click che chiamerà la funzione foo!

via GregWolejko


Tags: , , , , ,

Post simili

Comments