Nate's Programming Blog

I discovered a new javascript technique recently thanks to James, this site and this site. It allows you to add and remove events without actually modifying the event function. The old way of doing this would be something like this:

window.onload = function() { … };

This is not good, because if another class in maybe some library you imported wanted to add an onload event, this would overwrite it or be overwritten depending on the load order. Well all newer browsers (with the exception of IE on Mac) allow you to access an event handler function, which allows you to add events without overwriting the event function. I wrote a javascript class to easily reuse this functionality:

/**
* This is a javascript class that handles modifying events on javascript objects. It allows you to add and remove
* multiple events like ‘onclick’ and ‘onchange’ to html elements. This is provided in replace of changing the
* function that the event is set to, for example:
*
* window.onload = function () { … };
*
* This is bad because no other object can now set onload events without overridding the current event. This class
* solves that problem.
*
* created by: Nate Minshew
* date created: 09/06/2005
*/
function EventHandler() {

/**
* Adds an event to the specified object.
*
* obj – Object the event is to be applied to.
* evType – Type of event to add, ei. click for onclick.
* fn – Function to call for the event.
*
* created by: Nate Minshew
* date created: 09/06/2005
*/
function addEvent(obj, evType, fn) {
if (obj.addEventListener) {
obj.addEventListener(evType, fn, false);
return true;
} else if (obj.attachEvent) {
var r = obj.attachEvent(“on”+evType, fn);
return r;
} else {
return false;
}
}

/**
* Removes an event from the specified object.
*
* obj – Object the event is to be removed from.
* evType – Type of event to remove, ei. click for onclick.
* fn – Function the event was calling.
*
* created by: Nate Minshew
* date created: 09/06/2005
*/
function removeEvent(obj, evType, fn){
if (obj.removeEventListener) {
obj.removeEventListener(evType, fn, false);
return true;
} else if (obj.detachEvent) {
var r = obj.detachEvent(“on”+evType, fn);
return r;
} else {
return false;
}
}

this.addEvent = addEvent;
this.removeEvent = removeEvent;

}

Using this class will allow you to be able to add and remove events without stepping on any other javascript code’s toes.


Name (required)

Email (required)

Website

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

Feel free to leave a comment

top