Search code examples
javascriptember.jshbs

How to dynamically add click handler to Ember Octane component - dynamic "on" modifier


I have a situation where I need to make a component and it has some logic to either render as a button or as a DIV depending on if it has a link.

{{#let
  (if
    this.hasLink
    (component "external-library-button$special-button")
    (element "div")
  )
  as |MaybeAButton|
}}
    <MaybeAButton
      {{on "click" this.onClick}} // can this be dynamically added?
    >
      ...lots of nested code
    </MaybeAButton>
{{/let}}

I tried to do add it dynamically but I get an error that "on" is not in scope.

{{(if this.hasLink (modifier on "click" this.onClick))}}

What's a good way to dynamically add a click handler? I'd like to not add a listener if it won't be interactive.


Solution

  • If you're using [email protected]+, you can conditionally apply the modifier using the modifier helper.

    it would look like this

    <a {{ (if this.hasLink (modifier on "click" this.onClick) ) }}>
      ...
    </a>
    

    You could also use a let, if you want to make reading the modifier a bit more focused

    {{#let (modifier on "click" this.onClick) as |handleClick|}}
      <a {{ (if this.hasLink handleClick) }}>
        ...
      </a>
    {{/let}}
    

    NOTE: at the time of writing, I do not recall if it's on or 'on' -- may depend on the type of file you're in (loose mode or strict mode)