/ Uncategorized

Event Delegation

If you come along one of those instances where you want to disable an event listener you have many options. One of them would be to assign null to the event handler.


document.onclick = null;

Thinking ahead what if you are using event delegation and you want to deactivate only one event from beeing triggered?

There exists the stopPropagation() method which you could put to use.

event.stopPropagation ();

But wouldn't that prevent all parent elements from receiving the event bubble? Not nearly specific enough for my liking.

In order to solve this puzzle I would use a object oriented approach. This approach simulates the deactivation of single events. We achieve that by overriding the specific method or methods that get invoked when elements of the HTML document trigger an event.

document.onclick = function (event) {
var e, target;

e = event || window.event; 
target = e.target || e.srcElement;

if (target.id === "stuffyDOMElement") {
    mObj_Instance.doStuff ();

if (target.id === "biffyDOMElement") {
    mObj_Instance.doBiff ();


// Singelton
var myObject = {

// Property literal, aka method
doStuff: function () {
    // put meaningful code here

doBiff: function () {
    // Deactivate stuffyDOMElement.onclick actions
    mObj_Instance.doStuff = function () {};

reActivateDoStuff: function () {
    // Re-instantiate from the original Object
    mObj_Instance = Object.beget (myObject);


// Prototypal inheritance by Crockford
if (typeof Object.beget !== 'function') {
Object.beget = function (o) {
var F = function () {};
F.prototype = o;
return new F ();

// initial instantiation
var mObj_Instance = Object.beget (myObject);

After you click on the Biffy HTML element -which could be a input button- all elements even our Stuffy HTML element will still listen to mouse clicks. But since we overrode the doStuff() method with an empty function it seems like the StuffyDOMElement doesn't receive clicks anymore.

To reactivate the initial behaviour thus resurrecting both methods from the original myObject object you just have to instantiate myObject again. I prepared this functionality within the reActivateDoStuff() method.

If you have another more elegant solution at hand why don't share it in the comments below? Also please feel free to subscribe to my RSS feed as I will post more insights on Web Development soon.

Event Delegation
Share this