1

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:

  • I know the code above will not work. It's only for purpose illustration.
  • I know button can use disabled attribute to achieve this. In my original work, it is actually a <a/> which doesn't have disabled. I need to keep it as <a/> tag for css purpose.
  • I wish to keep the button in page no matter it is disabled or not. This is kind of web page convention. In that case, user will know that he must missing something when the button is disabled.
Rvervuurt
  • 8,589
  • 8
  • 39
  • 62
glenlivet1986
  • 260
  • 3
  • 12

1 Answers1

6

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)).

Daniel Kmak
  • 18,164
  • 7
  • 66
  • 89
  • ty. Can you explain more about `(mut undefProp)` thing? or can you give me a link to read more about it? I have no idea of this and I cannot find any ref from ember website. – glenlivet1986 Nov 19 '15 at 10:59
  • so what is `undefProp` here? – glenlivet1986 Nov 19 '15 at 11:14
  • does it just stand for a undefined property in controller/component? It self has no special meaning in Ember.js, correct? – glenlivet1986 Nov 19 '15 at 11:17
  • `undefProp` is just random undefined property. Yes, it has no special meaning. It's just used to create a mocked action which does nothing. – Daniel Kmak Nov 19 '15 at 11:18
  • 2
    Cheers! Now it's super clear. Is it kind of workaround? I'm just curious why it can't work as `{{action (if publishable 'publish')}}`, which is more readable. In your opinion, is this enhancement possible? – glenlivet1986 Nov 19 '15 at 11:21