【问题标题】:How do you use an unbound property as the argument of an if helper in a template with Ember.js?如何在 Ember.js 的模板中使用未绑定的属性作为 if 助手的参数?
【发布时间】:2014-10-27 18:34:22
【问题描述】:

我有一个 Handlebars 助手,它接受一个数字并返回一个类名。我只想在 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

【问题讨论】:

    标签: ember.js


    【解决方案1】:

    您可以创建一个计算属性并将其添加到视图的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 foo}}{{/unboundif}}
    【解决方案2】:

    为此有一个助手。它叫unboundIf:见documentation

    你可以这样使用它:

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

    表达式只计算一次。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-09
      • 1970-01-01
      • 2013-05-19
      • 2015-06-24
      • 1970-01-01
      • 2013-01-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多