I am wondering if the following is a good concideration. There might be several links on a page with a data-rel attribute that could be static or dynamically added with javascript. Instead of adding an eventlistener to each of those I am thinking about adding an eventlistener to the document. I don't want to use jQuery.
Is the following good, or is there a better do add events to dynamically added ellements?
var api = {
function addEvent (evnt, el, func) {
if (el.addEventListener) { // W3C DOM
el.addEventListener(evnt,func,false);
} else if (el.attachEvent) { // IE DOM
el.attachEvent('on' + evnt, func);
} else { // No much to do
el[evnt] = func;
}
}
, removeEvent : function removeEvent (evnt, el, func) {
if (el.removeEventListener) { // W3C DOM
el.removeEventListener(evnt,func,false);
} else if (el.detachEvent) { // IE DOM
el.detachEvent('on' + evnt, func);
} else { // No much to do
el.splice(evnt, 1);
}
}
, checkWhatIsClicked: function checkIfDialog (e) {
var el = e.srcElement || e.target
, dataCallback = el.getAttribute('data-callback')
, dataRel = el.getAttribute('data-rel');
if (dataRel !== null) {
switch (dataRel) {
case 'alert':
e.preventDefault();
dialogBox.alert();
break;
case 'dialogBox':
e.preventDefault();
dialogBox.dialog();
break;
case 'prompt':
e.preventDefault();
dialogBox.prompt();
break;
}
} else if (dataCallback !== null && el.className.indexOf('dialog-answer') > -1) {
if (typeof window[dataCallback] === 'function') {
var result = el.getAttribute('data-result');
window[dataCallback](result, el);
}
}
}
};
api.addEvent('click', window.document, api.checkWhatIsClicked);
addEvent(), click(), removeEvent()
? Now that doesn't make sense. Why not just invoke the listener directly? – Bergi Apr 3 at 19:02