You can use addEventListener to bind events and pass in the callback function.
Versions later than Mozilla 0.9.1 and Netscape 6.1 not only support passing function references, but also allow the objects with the handleEvent method to be directly used as the second parameter of the addEventListener method.
This is also described in the interface definition of DOM Level 2:
Http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-EventListener
This feature can be used to register any object as an event handler as long as it has the handleEvent method.
var o = {
handleEvent: function () {
alert ('handleEvent executed');
}
};
element.addEventListener ('click', o, false);
When defining the object encapsulation, you can directly pass the this pointer:
var o = {
bind: function () {
element.addEventListener ('click', this, false);
},
handleEvent: function () {
alert ('handleEvent executed');
}
};
IE9 is the first browser in the IE family that supports addEventListener + handleEvent. Versions before IE9 did not even support addEventListener. Compatibility issues need to be resolved through attribute detection:
function on (el, ev, fn, bubble) {
if (el.addEventListener) {
try {
el.addEventListener (ev, fn, bubble);
}
// BlackBerry and other systems do not support the handleEvent method
catch (e) {
if (typeof fn == 'object' && fn.handleEvent) {
el.addEventListener (ev, function (e) {
// The first parameter is the event object
fn.handleEvent.call (fn, e);
}, bubble);
} else {
throw e;
}
}
} else if (el.attachEvent) {
// Check if the parameter has handleEvent method
if (typeof fn == 'object' && fn.handleEvent) {
el.attachEvent ('on' + ev, function () {
fn.handleEvent.call (fn);
});
} else {
el.attachEvent ('on' + ev, fn);
}
}
}
Finish.
Reference materials:
http://www.thecssninja.com/javascript/handleevent
http://topic.csdn.net/t/20040628/14/3128262.html
"Source of this article: Mango Station, original: http://www.mangguo.org/addeventlistener-and-handleevent/"