Lately I've been studying a lot of javascript samples, both with/without libraries, jQuery to mention one.
As an old JavaScript developer, I learned early to make use of unobtrusive javascript where one were adding mouse click events to a global handler using document.onclick = mylib.document_onclick;
Then, by tagging any element with a custom attribute/property/expando, I been able to deal with all kinds of functions in a very simple way.
// HTML
<div class='menulink logout' data-mc='logout'> Logout </div>
<a class='menulink' data-mc='ajax' data-target='main-content-div' href='page/'>Start page 1</a>
<a class='menulink' data-mc='ajax' data-target='main-content-div' href='page/'>Start page 2</a>
// JS
document_onclick: function (e) {
e = getEvObj(e); // custom method to get event object
var evSrcTag = getSrcObj(e); // custom method to get source element
//mouseclick
if (evSrcTag.getAttribute('data-mc') != undefined) {
switch (evSrcTag.getAttribute('data-mc')) {
case 'logout':
if (!confirm(myconfig.msg['asklogout'])) {
return cancelEv(e); // custom method to cancel the event
}
break;
case 'ajax':
//process ajax request as javascript is available, cancel default event (href)
//case ......
}
}
},
Today I see a lot solutions where the event is bound/attached straight to a specific element.
It appears to quikly become a long list of handlers to be added, together with individual functions and class names tied/added.
// HTML
<a id="anchor1" href="#">create link dynamically</a>
<a id="anchor2" href="#">create link dynamically</a>
<a id="anchor3" href="#">create link dynamically</a>
// JS
$(function(){
$("#anchor1").click( function() {
$("#anchor1").append('<a class="myclass" href="page/test1">test1</a>');
});
$("#anchor2").click( function() {
$("#anchor2").append('<a class="myclass" href="page/test2">test2</a>');
});
$("#anchor3").click( function() {
$("#anchor3").append('<a class="myclass" href="page/test3">test3</a>');
});
});
Referring to the way setting up handlers, is one approach better than the other, and if so, which one is and why?