Last active
August 29, 2015 14:07
-
-
Save thomasthesecond/519315ef4c9ea43dbaa8 to your computer and use it in GitHub Desktop.
RequireJS module for `addEventListener` method.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
define([], function() | |
{ | |
/** | |
* Loops through each event type, attaches the listener, and creates a | |
* fallback with `attachEvent`. | |
* @param {object} el The element on which to attach the listener. | |
* @param {array} type A array containing the event type(s) to | |
* listen for. | |
* @param {function} listener The function that runs when the event type | |
* is called. | |
*/ | |
function addEventListener(el, type, listener) | |
{ | |
for (var i = 0, length = type.length; i < length; i++) { | |
if (el.addEventListener) { | |
el.addEventListener(type[i], listener, false); | |
} else { | |
el.attachEvent('on' + type[i], listener); | |
} | |
} | |
} | |
return { | |
/** | |
* Public method; call using `addEvent.init(el, type, listener);` | |
* @param {object} el The element on which to attach the listener. | |
* @param {string} type A string containing the event type(s) to | |
* listen for. Multiple events should be | |
* separated by a space. The string gets | |
* converted to an array by the `split` method. | |
* @param {function} listener The function that runs when the event type | |
* is called. | |
*/ | |
init: function(el, type, listener) | |
{ | |
type = type.split(' '); | |
if (typeof el.length === 'undefined' || el.length === 0) { | |
addEventListener(el, type, listener); | |
} else { | |
for (var i = 0, length = el.length; i < length; i++) { | |
addEventListener(el[i], type, listener); | |
} | |
} | |
} | |
}; | |
}); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Usage | |
* | |
* Grab an element with `document.querySelector` or `document.querySelectorAll` | |
*/ | |
'use strict'; | |
define(['addEvent'], function(addEvent) | |
{ | |
var selectors = { | |
menuButton: document.querySelector('.js-menu-button') | |
}; | |
return { | |
init: function() | |
{ | |
addEvent.init(selectors.menuButton, 'click touchstart', function(event) | |
{ | |
// Do something | |
event.preventDefault(); | |
}); | |
} | |
}; | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment