我将首先解释我想做什么,因为也许有一个比我正在尝试的更好的解决方案:我正在使用引导网格布局,并尝试根据我的模型使用余烬以编程方式创建新的行和列。我现在拥有的是:
{{#each model}}
{{#if beginRow}}
<div class="row">
{{/if}}
<div class="col-sm-3">
stuff
</div>
{{#if endRow}}
</div>
{{/if}}
{{/each}}
我根据一个计数器制作了getinRow
和endRow
计算属性,我想在每次遍历每个计数器时递增该计数器。
App.MyController = Ember.ArrayController.extend({
currentIndex: 0,
beginRow: function() {
if(this.get('currentIndex')%3 == 0) {
return true;
} else return false;
}.property('currentIndex'),
endRow: function() {
if(this.get('currentIndex')%3 == 0) {
return true;
} else return false;
}.property('currentIndex'),
actions: {
incrementCurrentIndex: function() {
this.incrementProperty('currentIndex');
},
}
});
我认为这会起作用,但是这里缺少的部分是在每个循环调用增量CurrentIndex
方法。这可能吗?我刚刚想到的一个想法是使用自定义车把助手来增加属性,但我不确定它是否可以访问控制器。对于我正在尝试做但我忽略了的事情,有更好的替代方案吗?谢谢!
找到了一个很好的解决方案!我没有使用我的控制器,而是使用_view. contentIndex
在每个助手中获取我所在的索引,并将该值发送到两个Handlebar Helper,如下所示:
{{#each model}}
{{isNewRow _view.contentIndex 3}}
<div class="col-sm-4">
stuff
</div>
{{isEndOfRow _view.contentIndex 3}}
{{/each}}
助手根据索引和列数计算这是否应该是一个新行:
Ember.Handlebars.registerBoundHelper('isNewRow', function(index, columns) {
if(index%columns == 0)
return new Ember.Handlebars.SafeString('<div class="row">');
});
Ember.Handlebars.registerBoundHelper('isEndOfRow', function(index, columns) {
if(index%columns == columns-1)
return new Ember.Handlebars.SafeString('</div>');
});
希望这能帮助其他有类似问题的人!
我建议将您的数组划分为包含3个元素的小数组。句柄不是编写逻辑的好地方。始终尝试将您的逻辑移动到您的控制器中。
在你的模板
{{#each slice in slicedArray}}
<div class="row">
{{#each item in slice}}
<div class="col-sm-3">
{{!-- Do your stuff --}}
</div>
{{/each}}
</div>
{{/each}}
给你的控制器
App.MyController = Ember.ArrayController.extend({
slicedArray: function(){
// slice your array into small ones and return it
}.property('model');
});