gpt4 book ai didi

javascript - Backbone.js 我们可以没有任何 tagName 吗?

转载 作者:搜寻专家 更新时间:2023-11-01 04:44:01 25 4
gpt4 key购买 nike

我刚开始使用 backbone.js,我注意到的一件事是有时我不想要任何 tagName包含/封装我的 View 的模板代码。如果我把它留在 '''span' ,我变得不必要divspan在我的代码中。

我发现的替代方法是从我的模板中删除包含标签(在我的示例中为 <div class="photo_box">,如下所示),并将其用作 tagName在我看来。大多数时候,这个标签会包含一个类(.photo_box),我仍然需要执行一个addClass。到(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;
}


});

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>

结果

<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>

最佳答案

你总是可以使用 setElement :

setElement view.setElement(element)

If you'd like to apply a Backbone view to a different DOM element, use setElement, which will also create the cached $el reference and move the view's delegated events from the old element to the new one.

忘记tagName完全:

PhotoListItemView = Backbone.View.extend({
template: _.template($('#tpl-PhotoListItemView').html()),
render: function() {
this.setElement(this.template(this.model.toJSON()));
return this;
}
});

演示:http://jsfiddle.net/ambiguous/XWEMg/


顺便说一句, <span> 由于其有限的 permitted content ,对于容器(即使是临时容器)来说是一个糟糕的选择;如果您开始将任意 HTML 放入 <span> 中,您冒着浏览器重新排列 HTML 以获得有效内容的风险. <div> 是一个更安全的选择,因为它几乎可以容纳任何东西。

关于javascript - Backbone.js 我们可以没有任何 tagName 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11178816/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com