Browse Source

Added addEventListeners() and addListenerToEvents() methods. Moved isElement into a first class function then added back to the returned Utils object.

dev
Bryan Miller 5 years ago
parent
commit
29757a9284
1 changed files with 38 additions and 15 deletions
  1. +38
    -15
      app/js/common/Utils.js

+ 38
- 15
app/js/common/Utils.js View File

@@ -1,3 +1,22 @@

function isElement(el){
// Code based on...
// https://stackoverflow.com/questions/384286/javascript-isdom-how-do-you-check-if-a-javascript-object-is-a-dom-object
try {
// Using W3 DOM2 (works for FF, Opera and Chrome)
return el instanceof HTMLElement;
} catch(e) {
// Browsers not supporting W3 DOM2 don't have HTMLElement and
// an exception is thrown and we end up here. Testing some
// properties that all elements have (works on IE7)
return (typeof(el) === "object") &&
(el.nodeType === 1) &&
(typeof(el.style) === "object") &&
(typeof(el.ownerDocument) === "object");
}
}


const utils = {
isInt:function(v){
if (isNaN(v)){
@@ -7,21 +26,25 @@ const utils = {
return (x | 0) === x;
},

isElement:function(el){
// Code based on...
// https://stackoverflow.com/questions/384286/javascript-isdom-how-do-you-check-if-a-javascript-object-is-a-dom-object
try {
// Using W3 DOM2 (works for FF, Opera and Chrome)
return el instanceof HTMLElement;
} catch(e) {
// Browsers not supporting W3 DOM2 don't have HTMLElement and
// an exception is thrown and we end up here. Testing some
// properties that all elements have (works on IE7)
return (typeof(el) === "object") &&
(el.nodeType === 1) &&
(typeof(el.style) === "object") &&
(typeof(el.ownerDocument) === "object");
}
isElement:isElement,
addEventListeners(el, listeners){
if (!isElement(el))
throw new TypeError("Can only attach listeners to HTMLElement objects.");
Objects.keys(listeners).forEach((key) => {
el.addEventListener(key, listeners[key]);
});
},

addListenerToEvents(el, enames, listener){
if (!isElement(el))
throw new TypeError("Can only attach listeners to HTMLElement objects.");
if (!(enames instanceof Array))
throw new TypeError("Expected an array of event name strings.");
if (typeof(listener) !== 'function')
throw new TypeError("Listener expected to be a function.");
enames.forEach((name) => {
el.addEventListener(name, listener);
});
},

range:function(a, b, step){

Loading…
Cancel
Save