Skip to content

Commit

Permalink
conditional event handling (#1894)
Browse files Browse the repository at this point in the history
  • Loading branch information
NullVoxPopuli authored Jan 14, 2025
1 parent d6e6b61 commit 9d0ea3d
Show file tree
Hide file tree
Showing 3 changed files with 72 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import Component from '@glimmer/component';
import { tracked } from '@glimmer/tracking';
import { on } from '@ember/modifier';

export default class Incrementer extends Component {
@tracked clicks = 0;
@tracked enableIncrement = true;

handleClick = () => this.clicks++;
toggle = () => this.enableIncrement = !this.enableIncrement;

<template>
<button {{ (if this.enableIncrement (modifier on 'click' this.handleClick)) }}>
Click me!
</button>

<button {{on 'click' this.toggle}}>
Toggle Clicking
</button>

<br>
Increment Enabled: {{this.enableIncrement}}<br>
Clicked: {{this.clicks}}
</template>
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import Component from '@glimmer/component';
import { tracked } from '@glimmer/tracking';
import { on } from '@ember/modifier';

export default class Incrementer extends Component {
@tracked clicks = 0;
@tracked enableIncrement = true;

handleClick = () => this.clicks++;
toggle = () => this.enableIncrement = !this.enableIncrement;

<template>
<button {{on 'click' this.handleClick}}>
Click me!
</button>

<button {{on 'click' this.toggle}}>
Toggle Clicking
</button>

<br>
Increment Enabled: {{this.enableIncrement}}<br>
Clicked: {{this.clicks}}
</template>
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
Events can be conditional by combining `if` syntax in _modifier space_.

An important thing to keep in mind when writing conditional modifiers is the wrapping parenthesis:

```hbs
<button {{ (if condition (modifier on 'click' handleClick)) }}>
Click me!
</button>
```
rather than
```hbs
<button {{if condition (modifier on 'click' handleClick)}}>
runtime error! 'if' is not a modifier
</button>
```


This exercise has set up two buttons: one to increment a value when clicked, and one to enable incrementing of that value.

<p class="call-to-play">
Adjust the code so that the toggle clicking button toggles the ability to increment the "Clicked" count.
</p>

0 comments on commit 9d0ea3d

Please sign in to comment.