Ever since JQuery came along a few years ago I’ve been using it in all my client-side scripts. Initially I used the ‘$() syntax to grab and manipulate objects this, to me, is the ‘old skool’ paradigm of explicitly wiring up button events to functions:
<button onClick='myFunction(this);' ... />
with a related function:
function myFunction(obj){
alert('this is how old-timers like me do it!')
}
Some of my colleagues prefer to do the attaching of scripts to events a la JQuery:
$(document).ready(
$("#myButton").click(
function(event){
alert('this is the newer JQuery way of doing things');
}
);
);
Initially I found the overly-bracey JQuery syntax with its reliance on anonymous functions etc. difficult to read, but my eyes and brain have adjusted so I’m happy with either way now. I would however like our codeshop to be consistent. Does anyone have any opinions on which approach is ‘better’?
I think the second approach is cleaner for several reasons :
it really allows you to separate content and behaviour, that is you can define your content’s structure first and only later take care of the specific behaviour… This is especially helpful if your team involves different technical profiles (somebody takes care of the raw HTML, somebody else is the Javascript expert …)
This really helps maintenance, as you know where to look for the potentially buggy javascript if something goes wrong , instead of having to look through the whole HTML.
when your HTML is actually dynamic (generated on server-side, à la PHP or ASP.NET), it is actually quite painful to have to include those client-side elements in the HTML you generate… This is a very common source of errors, therefore it is good to have the javascript out of the way.