尝试在迭代ember集合时访问索引值,可以像这样访问索引值:
{{_parentView.contentIndex}}
但是当尝试在compare helper中访问相同的索引值时,看不到该值。任何有关如何访问助手内部索引的帮助都将受到赞赏。
代码:
{{#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);
}
});
答案 0 :(得分:1)
传递给助手的第一个参数实际上是一个字符串,它表示要解析值的属性的路径。因此,要获得lvalue
,您必须按照这些方式执行某些操作,请参阅http://jsfiddle.net/pangratz666/DLPgN/:
Ember.Handlebars.registerHelper('compare', function(path, compareValue, options) {
...
// options.contexts[0] is the passed context
// path is the path to the property of the context
var lvalue = Ember.getPath(options.contexts[0], path);
var rvalue = parseInt(compareValue, 10); // convert to number since it's a string
...
var result = operators[operator](lvalue, rvalue);
});