在迭代 ember 集合时尝试访问索引值,可以像这样访问索引值:
{{_parentView.contentIndex}}
但是当尝试在比较助手中访问相同的索引值时,看不到该值。任何有关如何访问助手内部索引的帮助将不胜感激。
代码:
{{#each App.SampleController}}
{{#view App.HomeView contentBinding="this"}}
Index : {{_parentView.contentIndex}}
{{#compare _parentView.contentIndex "0" operator="=="}}
{{/compare}
{{/view}}
{{/each}}
输出:
Index: 0 and the value getting passed into compare helper is `_parentView.contentIndex` as a string!
比较助手看起来像这样:
Ember.Handlebars.registerHelper('compare', function(lvalue, rvalue, options) {
if (arguments.length < 3)
throw new Error("Handlerbars Helper 'compare' needs 2 parameters");
operator = options.hash.operator || "==";
var operators = {
'==': function(l,r) { return l == r; },
'===': function(l,r) { return l === r; },
'!=': function(l,r) { return l != r; },
'<': function(l,r) { return l < r; },
'>': function(l,r) { return l > r; },
'<=': function(l,r) { return l <= r; },
'>=': function(l,r) { return l >= r; },
'typeof': function(l,r) { return typeof l == r; }
};
if (!operators[operator])
throw new Error("Handlerbars Helper 'compare' doesn't know the operator "+operator);
console.log("operator is "+ lvalue +" and "+rvalue);
var result = operators[operator](lvalue,rvalue);
console.log("result from compare registerHelper is "+ result);
if( result ) {
return options.fn(this);
} else {
return options.inverse(this);
}
});