Skip to content

Instantly share code, notes, and snippets.

@mcsheffrey
Created September 26, 2013 18:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save mcsheffrey/6718840 to your computer and use it in GitHub Desktop.
Save mcsheffrey/6718840 to your computer and use it in GitHub Desktop.
Init-Time Branching - JavaScript Patterns
// the interface
var utils = {
addListener: null,
removeListener: null
};
// the implementation
if (typeof window.addEventListener === 'function') {
utils.addListener = function (el, type, fn) {
el.addEventListener(type, fn, false);
};
utils.removeListener = function (el, type, fn) {
el.removeEventListener(type, fn, false);
};
} else if (typeof document.attachEvent === 'function') { // IE
utils.addListener = function (el, type, fn) {
el.attachEvent('on' + type, fn);
};
utils.removeListener = function (el, type, fn) {
el.detachEvent('on' + type, fn);
};
} else { // older browsers
utils.addListener = function (el, type, fn) {
el['on' + type] = fn;
};
utils.removeListener = function (el, type, fn) {
el['on' + type] = null;
};
}
@mcsheffrey
Copy link
Author

Not the best example (browser sniffing, etc) but a good JavaScript pattern to keep in mind.

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