Switching Events On & Off Globally

I ran into an interesting problem while searching the web for a solution to a bug Ive been encountering when attaching click event listeners on demand (to be discuss next week). The problem is, a developer attaches all their click events when the page loads, but at a certain point during the processing of the page, they want to disable all click events.

How to do it…

First create a global variable to handle the event toggle:

var myEventToggle = true;

var myEventWrapper = function(fx) {
	return function(e) {
		if (myEventToggle) {
			fx.apply(this, arguments);
		}
		else {
			return false; // if using element.onclick
			// YAHOO.util.Event.preventDefault(e); // in YUI 2
			// e.preventDefault(); // in YUI 3
			// Event.stop(e); // in Prototype
			// e.preventDefault(); in jQuery
		}
	};
};

Then use the myEventWrapper function when subscribing to events:

var myEventCallack = function(e) {
	// event callback code here
};

document.getElementById(myElementId).onclick = myEventWrapper(myEventCallack);

// or if using YUI 2

YAHOO.util.Event.on(myElementId, click, myEventWrapper(myEventCallack));

How it works…

The myEventToggle and myEventWrapper should be somewhere in the global namespace, so that they can be accessed anywhere. When attaching events, call myEventWrapper and pass it the function that would normally be the callback. The wrapper returns an anonymous function that will actually be assigned to the event callback. When the event fires, the anonymous function executes and evaluates the global myEventToggle variable. If the myEventToggle is true, then the arguments and execution context are passed to the original callback that was passed into myEventWrapper, and the event behaves normally. When myEventToggle is false, the anonymous function returns false or it should call the equivalent function available in your favorite framework, which prevents the default behavior of the click event.

Theres more…

I am not sure how useful turning off all click or some other type of events on a page is, but I do think this pattern could be useful. For example, if you have focus and blur events attached to elements in a form, and a submit event listener that submits the form via AJAX. When the submit event fires, you could use this pattern to turn the listeners attach to form elements on and off.