This is probably the most useful function on my JavaScript library. Browsers have different behaviors in regards on how to bind, unbind and fire events. So, before you start make sure you create your version (or find an open source library that has one). Here is the very simple version of a bind function:
function my_bind(elem, evtname, func)
{
if(typeof(elem)=="string")
elem = document.getElementById(elem);
if(elem.addEventListener)
elem.addEventListener(evtname, func, false);
else if(elem.attachEvent)
elem.attachEvent("on" + evtname, func);
}
Now most people will extend this function to contain some very old syntax to bind events, like:
elem["on" + evtname] = func;
This syntax probably dates back to the early IE (3.0?) and Netscape. Nobody uses those browsers anymore. See tip #1 and don't waste your time.
JavaScript uses a garbage collector to clean up after you leave the page, however, there is a dangerous mix of references between objects in the DOM (like an element) and objects on your JavaScript (like a function) that might cause a cross-reference that the Garbage Collector (GC) doesn’t know how to unwind. The safest way to prevent that from happening is to help the GC by doing some clean up of your own, the most important being to unbind every event that was dynamically bound. My solution is to create an array, and store the information for every bind call, and attach an event onunload of the window to do the clean up.
The code looks like this:
var dynbound = new Array(); function my_bind(elem, evtname, func) { dynbound.push(elem, evtname, func); ... }
function window_onunload() { for(var i = 0; i < dynbound.length; i+=3) my_unbind(dynbound[i], dynbound[i+1], dynbound[i+2]); dynbound = null; } my_bind(window, "unload", window_onunload);