Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditionally add action to element with Ember Handlebars

I've scoured the Internet for an answer to this problem but have found none. I have a custom SideNavigationLinkComponent that wraps an <li> around an <a> tag and possibly a <ul> of child links.

The anchor tag looks something like this:

 <a href="{{unbound menu.parent.link}}" {{action "toggle"}}>
    ...
 </a>

"Why aren't you using {{link-to}}?" you ask. It's because menu.parent.link isn't guaranteed to be a valid route; sometimes it's something like #nav-collapsible-44, which breaks {{link-to}}.

Anyway, the point of the anchor tag in the code above is to serve as either a top-level link to another Ember page or a button that causes a collapsible list of sublinks to drop down.

My problem is that as long as I have {{action "toggle"}} on the anchor tag, the link doesn't go anywhere (but the collapsibles work, which is part of what I want). So I need to be able to conditionally add an {{action}} so that I can create either links that go to other pages or buttons that cause dropdowns to expand depending on the value of some boolean condition I have.

I don't want to have to do this:

{{#if condition}}
  <a href="{{unbound menu.parent.link}}" {{action "toggle"}}>
    ...
  </a>
{{else}}
  <a href="{{unbound menu.parent.link}}">
    ...
  </a>
{{/if}}

which so far has been the only way I've found to solve this problem. There's a lot of HTML in the anchor tags and sure, I could use a partial to DRY this structure up a bit, but that's just putting band-aids on a banana split.

I've also tried

if(!condition){
  return true; 
}

in my "toggle" action but it had no effect.

like image 681
IGNIS Avatar asked Jan 15 '15 19:01

IGNIS


2 Answers

You can also use (optional) helper from ember-composable-helpers

<a {{action (optional (if foo (action "nextQuestion") null))}}>
like image 123
Blake Mills Avatar answered Sep 23 '22 05:09

Blake Mills


Use closure actions such as:

<a href="{{unbound menu.parent.link}}" onclick={{if condition (action 'toggle')}}> 
    ...
</a>
like image 31
ykaragol Avatar answered Sep 24 '22 05:09

ykaragol