I have to admit that I have always been a little confused on "proper" unobtrusive javascript. I get that you want to move the script out of your markup, and don't have the markup reference your script (other than the original script reference of course!) But I can't see how this works in practice.
I get how to make your markup not reference the code, but I feel dirty hard coding in DOM IDs in the script. Here is an example:
<script src="....awesome.js"></script>
<button id="primaryAction">Click me for something awesome!</button>
<labal id="resultText"></label>
//in awesome.js
awesome = function(){
init = function(){
//pretend we are doing something incredible here
//and then we hook the button up
$('#primaryAction').click(function(){
$('#resultText').val(result());
});
};
result = function(){
//here something awesome happens and we return the result
return "Joe";
};
return {
init: init
}
}();
That should be something pretty representative of what could be, right? So my confusion comes in two places.
- Where should I call awesome.init() from?
- I feels wrong to reference the control IDs from javascript, but it also feels wrong to have classes specified in the script and require the markup to use them for it to work. How should it be done? Both feel obtrusive to me. Should the init() function take something like
{button:'#primaryAction', result:'#resultText'}
But then again it comes to #1..Where should Init be called from?
If I am doing this fundamentally wrong, please guide me to the path.