让我们以下面的模板为例:
<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>
假设我使用 Backbone 渲染该模板并单击like-button触发以下功能:
选项 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*/);
选项 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();
您会推荐哪种方法?为什么?另外请考虑移动浏览器,在移动设备上重新渲染整个模板(如果模板有点大)是否太慢了?