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');
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?
Best practice is to use a templating engine (like Mustache.js or jQuery's built in templating engine) and classes, via .addClass.
But at the end, you just can't completely separate the V from the C (View from Controller - MVC), especially in html.
I think the best practice would be to use classes in jQuery and keep your css in a separate style sheet.
EDIT:
I would also add that learning straight from the horse's mouth works for me. I use http://api.jquery.com/ for almost everything I really need to understand jQuery related.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With