Nyx*_*nyx 4 javascript jquery backbone.js underscore.js
我刚开始使用backbone.js,我注意到的一件事是有时候我不希望任何tagName包含/封装我视图的模板代码.如果我离开它''或者'span',我得到不必要的div和span在我的代码.
我发现另一种方法是,以除去从模板中的含有标签(<div class="photo_box">在我的例子如下所示),并使用它作为tagName在我的视图.大多数情况下,这个标签将包含一个class(.photo_box),我仍然需要执行addClassto(this.el).我真的不喜欢散布我的模板代码.
还有另外一种方法吗?
JS
// Views
PhotoListView = Backbone.View.extend({
tagName: 'span',
render: function() {
_.each(this.model.models, function(photo) {
$(this.el).append(new PhotoListItemView({ model: photo }).render().el);
}, this);
return this;
}
});
PhotoListItemView = Backbone.View.extend({
tagName: 'span',
template: _.template($('#tpl-PhotoListItemView').html()),
render: function() {
$(this.el).html(this.template( this.model.toJSON() ));
return this;
}
});
Run Code Online (Sandbox Code Playgroud)
HTML
<!-- Templates -->
<script type="text/template" id="tpl-PhotoListItemView">
<div class="photo_box">
<div class="photo_container">
<img src="img/profiling/<%= photo_id %>.jpg" class='photo' />
</div>
</div>
</script>
Run Code Online (Sandbox Code Playgroud)
结果
<div id="photo_list">
<span>
<span>
<div class="photo_box">
<div class="photo_container">
<img src="img/profiling/f_001.jpg" class="photo">
</div>
</div>
</span>
<span>
<div class="photo_box">
<div class="photo_container">
<img src="img/profiling/f_002.jpg" class="photo">
</div>
</div>
</span>
</span>
</div>
Run Code Online (Sandbox Code Playgroud)
mu *_*ort 22
你可以随时使用setElement:
setElement
view.setElement(element)如果您想将Backbone视图应用于不同的DOM元素,请使用setElement,它还将创建缓存的
$el引用,并将视图的委托事件从旧元素移动到新元素.
tagName完全忘了:
PhotoListItemView = Backbone.View.extend({
template: _.template($('#tpl-PhotoListItemView').html()),
render: function() {
this.setElement(this.template(this.model.toJSON()));
return this;
}
});
Run Code Online (Sandbox Code Playgroud)
演示:http://jsfiddle.net/ambiguous/XWEMg/
另外,由于<span>容器内容有限,容器(即使是临时容器)的选择也很差; 如果您开始将任意HTML投入到浏览器中,那么您可能会冒着浏览器重新安排HTML以获得有效内容的风险<span>.A <div>是一个更安全的选择,因为它几乎可以容纳任何东西.
您无需手动添加类名.您可以使用该className属性:
PhotoListItemView = Backbone.View.extend({
tagName: 'span',
className: 'photo_box',
Run Code Online (Sandbox Code Playgroud)
顺便说一下,我推荐这个HTML结构:
<ul id="photo_list">
<li>
<img src="img/profiling/f_001.jpg" class="photo">
</li>
<li>
<img src="img/profiling/f_003.jpg" class="photo">
</li>
</ul>
Run Code Online (Sandbox Code Playgroud)