Quantcast
Channel: Ember.JS - Latest topics
Viewing all articles
Browse latest Browse all 4840

Using `or` to provide a default event handler for `on`

$
0
0

Hey there,

I’m making a ModalDialog component which takes a onOverlayClick argument. The passed in function will be called when the overlay is clicked (I’m sure you’re surprised :stuck_out_tongue:):

<div role="button" {{on "click" @onOverlayClick}}>
   {{!-- ... --}}
</div> 

Since on throws an error if it’s second argument (the function to call) doesn’t exist, a fallback event handler needs to be provided. Here is my first try:

<div role="button" {{on "click" (or @onOverlayClick (fn))}}>
   {{!-- ... --}}
</div> 

Unfortunately, fn cannot be called without arguments to create an empty function (I think it’d be great if it did), so I went ahead and created a helper that does just that.

I named it noop:

import { helper } from '@ember/component/helper';

export default helper(function noop() {
  return () => {};
});

Armed with nothing (very funny) I rewrote the template snippet as follows:

<div role="button" {{on "click" (or @onOverlayClick (noop))}}>
   {{!-- ... --}}
</div> 

This doesn’t work, however, and the following error is raised:

Compile Error: Unexpected Helper or @ 0…0

To me, this suggests that Glimmer doesn’t expect a helper call as an argument to or. If that is so, I’m not sure I understand why.

Slightly disappointed by the misbehavior of or, I replaced it with the mother of all conditionals, if:

<div role="button" {{on "click" (if @onOverlayClick @onOverlayClick (noop))}}>
   {{!-- ... --}}
</div>

That works but it’s needlessly verbose and more prone to typos.

Alternatively, I could create the “do nothing” fallback function in the backing class of the component, but it’s so far a template-only component and it’d be kind of funny to create a component class just to do that.

Can you explain why on wouldn’t work like above? If it’s the wrong idea, is there a way to provide the fallback function in template-land, that’s more elegant than my solution with if?

Thank you.

9 posts - 4 participants

Read full topic


Viewing all articles
Browse latest Browse all 4840

Trending Articles