【问题标题】:How do I bind multiple class names in Ember 1.13?如何在 Ember 1.13 中绑定多个类名?
【发布时间】:2015-08-04 21:00:16
【问题描述】:

弃用bind-attr,转而使用把手if 语句用于类名绑定;如何将多个类名绑定到一个元素?

文档指定了单个绑定类名的语法,而不是多个:

http://guides.emberjs.com/v1.13.0/templates/binding-element-class-names/

<div class={{if isEnabled 'enabled' 'disabled'}}>
    Warning!
</div>

哪个结果(当isEnabled=true):

<div class="enabled"}}>
    Warning!
</div>

但是如果我需要将其他类名绑定到这个元素呢?我试过了:

<div class={{if isEnabled 'enabled' 'disabled'}}{{if isNew 'new' 'old'}}>
    Warning!
</div>

and(带和不带分号)...

<div class={{if isEnabled 'enabled' 'disabled'; if isNew 'new' 'old'}}>
    Warning!
</div>

第一个是后进胜出,第二个甚至不编译。

【问题讨论】:

    标签: javascript ember.js


    【解决方案1】:

    {{if}} 助手周围加上引号:

    <div class="{{if isEnabled 'enabled' 'disabled'}} {{if isNew 'new' 'old'}}">
    </div>
    

    你也可以写一个助手来为你做一些工作。

    供参考,这在1.11 release blog post中有所提及。

    【讨论】:

    • 布亚卡沙。多谢。很快就会接受。
    【解决方案2】:

    就像框架中的许多事情一样,您可以通过多种方式做到这一点

    1) 你可以让它们都内联

    <div class="{{if isTrue 'red' 'blue'}} {{if isAlsoTrue 'bold' 'underline'}}">
        I have both classes
    </div>
    

    有些人可能会争辩,这会让你的模板充满逻辑。我不会因为这种方式责怪您,因为它只有两个类,但是当您扩展项目时,您可能需要考虑选项 2...

    2)你可以使用组件的classNameBindings,

    <script type="text/x-handlebars" id="components/my-cool-dealy">
        <span>I love JSFiddle</span>
    </script>
    
    
    App.MyCoolDealyComponent = Ember.Component.extend({
        classNameBindings: ['category', 'priority'],
        category: function() {
            //logic here
            return "blue";
        }.property(),
        priority: function() {
            //logic here
            return "underline";
        }.property()
    
    });
    

    Here is a JSFiddle of both ways

    【讨论】:

    • 我认为我需要一个解决方案,它可以避免为我想要绑定类名的每个元素创建一个组件。我正在尝试编写一个助手,但无法找到一种简洁的方式来处理三元运算。我最终得到的并不比这里的例子更好:{{bind-class (if colorSwitch "color-one" "color-two") (if sizeSwitch "size-one" "size-two")}}
    • 你可以试试这样的:Ember.Handlebars.helper('myThing', function(value, options) { var color = value.colorSwitch ? "color-one" : "color-two"; var size = value.sizeSwitch ? "size-one" : "size-two"; return color + " " + size; }); &lt;div class="my-thing {{myThing myThingModel}}"&gt;{{myThingModel.title}}&lt;/div&gt;
    • 或者这个:Ember.Handlebars.helper('myThing', function(value, options) { var color = value.colorSwitch ? "color-one" : "color-two"; var size = value.sizeSwitch ? "size-one" : "size-two"; var title = value.get('title'); return new Ember.Handlebars.SafeString('&lt;div class="my-thing' + color + size '"&gt;' + title +'&lt;/div&gt;') }); {{myThing myThingModel}}
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-11-26
    • 1970-01-01
    • 2015-10-06
    • 1970-01-01
    • 1970-01-01
    • 2016-03-25
    • 1970-01-01
    相关资源
    最近更新 更多