如何在具有 Ember.js 的模板中使用未绑定属性作为 if 帮助程序的参数



我有一个车把助手,它接受一个数字并返回一个类名。我想仅在帮助程序存在时才运行foobar因为它可能不存在。我最初的尝试是:

{{#each content}}
    <div class="other_class {{#if foobar}}{{my_helper foobar}}{{/if}}"></div>
{{/each}}

这不起作用,因为 metamorph 会在if帮助程序所在的位置插入脚本标记占位符。我的第二次尝试是:

{{#each content}}
    <div class="other_class {{my_helper foobar}}"></div>
{{/each}}

这也不起作用,因为当 foobar 不存在时,字符串"foobar"会传递给my_helper

我知道执行{{unbound foobar}}将在不绑定值的情况下呈现值,因此没有脚本标签占位符。有没有办法以不受约束的方式使用if

可以创建一个计算属性并将其添加到视图classNameBindings,请参阅 http://jsfiddle.net/pangratz666/MvpUZ/:

App.MyView = Ember.View.extend({
    classNameBindings: 'omg'.w(),
    omg: function(){
        var foobar = Ember.getPath(this, 'content.foobar');
        return (foobar && foobar === 42) ? 'my-class-name' : null;
    }.property('content.foobar')
});

这有一个帮手。它被称为unboundIf:请参阅文档

你可以像这样使用它:

{{#unboundIf "content.shouldDisplayTitle"}}
  {{content.title}}
{{/unboundIf}}

表达式仅计算一次。

最新更新