Skip to content

Instantly share code, notes, and snippets.

@njif
Last active August 29, 2015 14:07
Show Gist options
  • Select an option

  • Save njif/7b0e0a642b16170f7992 to your computer and use it in GitHub Desktop.

Select an option

Save njif/7b0e0a642b16170f7992 to your computer and use it in GitHub Desktop.
Cross-browser event listener. This technique makes use of 3 patterns: closure + singleton + lazy loading
// http://javascriptrules.com/2009/07/22/cross-browser-event-listener-with-design-patterns/
var addEvent = (function () {
var setListener;
return function (el, ev, fn) {
if (!setListener) {
if (el.addEventListener) {
setListener = function (el, ev, fn) {
el.addEventListener(ev, fn, false);
};
} else if (el.attachEvent) {
setListener = function (el, ev, fn) {
el.attachEvent('on' + ev, fn);
};
} else {
setListener = function (el, ev, fn) {
el['on' + ev] = fn;
};
}
}
setListener(el, ev, fn);
};
}());
@njif
Copy link
Author

njif commented Oct 14, 2014

closure + singleton + lazy loading This technique makes use of 3 patterns:
closure is defined by nested functions (lines 1 and 4) where the inner function (line 4) has access to its outer function variable setListener (line 2), it is invoked on line 22.
singleton is defined by using a single variable (line 2) that defines a function on lines 7, 11 and 15. It is checked on line 5 and always invoked on line 20.
lazy loading is used here for assigning the singleton variable when demanded as opposed to immediately after singleton definition.
pros: no time consuming when script is loaded, first execution (closure) is very fast as it only returns a function, event listener attacher is defined only once on demand.
cons: it can be a bit obscure by mixing up 3 different techniques, after the first invocation every subsequent invocation has a verification on line 5 which will always return false however this is very subtle and also very cheap in JavaScript.
Initial execution cost as it is executed right after loading, but considering its size and complexity can barely be noticed. Can be a bit obscure for beginners unfamiliar with closures. For those I suggest reading Douglas Crockford’s Private Members in JavaScript (http://www.crockford.com/javascript/private.html). Closure consumes more memory because it carries with them the containing function’s scope.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment