Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are best practices to maintain separation of concerns when building HTML with JavaScript?

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?

like image 415
retrodrone Avatar asked Apr 21 '11 19:04

retrodrone


2 Answers

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.

like image 110
Zirak Avatar answered Sep 20 '22 10:09

Zirak


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.

like image 28
Code Maverick Avatar answered Sep 20 '22 10:09

Code Maverick