I’m currently learning jQuery by reading jQuery in Action.
The book discusses separation of concerns by using ‘Unobtrusive JavaScript.’ I grok that keeping behavior specified by JavaScript out of the <body> tree is good form and goes a long way toward maintainability.
However, the benefits of using that approach seems to be negated when looking at dynamic HTML generation with jQuery, such as this example:
$('<img>',
{
src: 'images/little.bear.png',
alt: 'Little Bear',
title:'I woof in your general direction',
click: function(){
alert($(this).attr('title'));
}
})
.css({
cursor: 'pointer',
border: '1px solid black',
padding: '12px 12px 20px 12px',
backgroundColor: 'white'
})
.appendTo('body');
- from jQuery in Action, 2nd Edition
Here, we’re mixing structure (the new <img> element), style (with the call to css()), and behavior (by setting the click attribute value.) So, we no longer have separation of concerns, even though this block is placed in the <head> of the document.
Is my understanding correct? What are best practices to mitigate this? Is it common to refer to external .css and .js resources when doing this type of HTML generation in practice?
Your missing the point here.
With unobstrusive Javascript the main aim is that in case if Javascript fails to load or execute, how will your application respond? That’s the key thing as people have Javascript disabled in many pages, so will your application show any content and respond in a normal fashion or would just go dead?
You can’t really separate the View from the Controller but unobstrusive Javascript helps in that direction. But the real benefit is resilience.
Also if you want good abstraction, use KnockoutJS. I cannot really emphasize any less and I can’t imagine creating huge websites with great client-side code without a similar library.