ember.jshtmlbars

How to bind action only under certain condition [Ember.js]


I just want to know, is there some way I can achieve the below purpose.

<button class="{{unless publishable "button-disabled"}}" {{if publishable (action "publish")}}>Publish</button>

Of course, it can be done in action method. I just think it could keep code drier if it can be done in template.

NOTE:


Solution

  • It is possible using {{mut}} in combination with {{action}} helper:

    <button {{action (if publishable 'publish' (action (mut undefProp)))}}>Publish</button>
    

    Working demo.

    You can read more about this specific use case (mut converts to function) in this blog post.

    Explanation:

    We use action helper and action which we pass to that helper will be computed - based on if condition.

    If condition evaluates to true we return 'publish' which is simply action name.

    If condition evaluates to false then we pass action which does nothing - we use something like workaround: (action (mut undefProp)).