Lets take for example the following template:
<div class="picture">
<img src="<%= model.get("url") %>"></img>
<p class="author"><%= model.get("author") %></p>
<p class="date"><%= model.get("date") %></p>
<div class="likers"><%= some logic that outputs a nice list of people that have liked this picture %></div>
<button class="like-button <%= model.get("is_liked") ? 'active' : '' %>"><%= model.get("is_liked") ? 'You liked this picture' : 'Click here to like this picture' %></button>
</div>
Lets say I render that template using Backbone and clicking the like-button triggers the following function:
Option A:
var me = "Peeter";
var model; //refrence to the model
var likers = model.get("likers");
model.get("is_liked") ? likers.remove(me) : likers.add(me); //Add/remove me
model.set({
"is_liked" : !model.get("is_liked"), //Toggle state
likers : likers
});
var $button = $(".like-button")
var $likers = $(".likers");
$button.toggleClass("active");
$button.hasClass("active") ? $button.text('You liked this picture') ? $button.text('Click here to like this picture');
$likers.text(/* copy/paste the logic that's in the template to render the list of likers*/);
Option B:
var me = "Peeter";
var model; //refrence to the model
var template; //refrence to the template declared at the top of this question
var likers = model.get("likers");
model.get("is_liked") ? likers.remove(me) : likers.add(me); //Add/remove me
model.set({
"is_liked" : !model.get("is_liked"), //Toggle state
likers : likers
});
template.render();
Which one of the methods would you recommend? Why? Also please take into count a mobile browser, is re-rendering an entire template (if the template was a bit bigger) a bit too slow on a mobile device?
This is a question that cannot be answered in general and some profiling for your specific use case will certainly help.
But as a general answer I think you have to review to following points:
For more detais, please check these links: