js文件;
var dataModel = Backbone.Model.extend({
defaults : {
dataID : 'unknown',
text : 'unknown'
}
});
var LinkCollection = Backbone.Collection.extend({
model : dataModel
});
假设集合大小为 8。我想一次显示 3 个。由于脚本的结构,我需要将集合项划分为单独的 div。
html 文件;
<div class="item">
<div class="carousel-subItem"> <-- Collection item #1
<span>{{dataID}}</span> <br /> <span>{{text}}</span>
</div>
<div class="carousel-subItem"> <-- Collection item #2
<span>{{dataID}}</span> <br /> <span>{{text}}</span>
</div>
<div class="carousel-subItem"> <-- Collection item #3
<span>{{dataID}}</span> <br /> <span>{{text}}</span>
</div>
</div>
<div class="item">
<div class="carousel-subItem"> <-- Collection item #4
<span>{{dataID}}</span> <br /> <span>{{text}}</span>
</div>
<div class="carousel-subItem"> <-- Collection item #5
<span>{{dataID}}</span> <br /> <span>{{text}}</span>
</div>
<div class="carousel-subItem"> <-- Collection item #6
<span>{{dataID}}</span> <br /> <span>{{text}}</span>
</div>
</div>
<div class="item">
<div class="carousel-subItem"> <-- Collection item #7
<span>{{dataID}}</span> <br /> <span>{{text}}</span>
</div>
<div class="carousel-subItem"> <-- Collection item #8
<span>{{dataID}}</span> <br /> <span>{{text}}</span>
</div>
</div>
我很难动态创建这个 html 结构。 (由于集合大小可能会有所不同......结构应该是完全动态的等;
{{#each dataModel}}
// code goes here, to create the above structure..
{{/each}}
最佳答案
也许这样的事情可以帮助你:
<script type="text/tempalte" id="template">
<% var len = items.length, group = 3, i; %>
<% for (i = 0; i <len; i += 1) { %>
<% if (i % group === 0) { %>
<div class="item">
<% } %>
<div class="carousel-subItem">
<span><%= items[i].dataID %></span> <br /> <span><%= items[i].text %></span>
</div>
<% if ((i % group === group-1) || (i === len -1)) { %>
</div>
<% } %>
<% } %>
</script>
我假设您想像使用 Backbone 一样使用 Underscore。项目集合看起来像这样,应该接近 Backbones 的观点:
var items = [
{ dataID : '1', text : 'bla' },
{ dataID : '2', text : 'blab' },
{ dataID : '3', text : 'gulp' },
{ dataID : '4', text : 'golp' },
{ dataID : '5', text : 'bla' }
];
// compiling the template
var template = _.template($('#template').html());
console.log(template(items));
输出如下所示:
<div class="item">
<div class="carousel-subItem">
<span>1</span> <br /> <span>bla</span>
</div>
<div class="carousel-subItem">
<span>2</span> <br /> <span>blab</span>
</div>
<div class="carousel-subItem">
<span>3</span> <br /> <span>gulp</span>
</div>
</div>
<div class="item">
<div class="carousel-subItem">
<span>4</span> <br /> <span>golp</span>
</div>
<div class="carousel-subItem">
<span>5</span> <br /> <span>bla</span>
</div>
</div>
我可以补充一点,更好的方法是使用一个 ItemView 来渲染“carousel-subItem”-div 和一个 CollectionView 来负责将渲染的 ItemView 组合到容器中。我认为 Backbone.Marionette 正好提供了这一点。也许您想检查一下。当然,您也可以自己构建类似的东西。
关于javascript - 主干显示集合(也许是集合的集合?),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13019231/