WebComp
Search…
Events
Events are a convenient way to communicate between different components on the page.

Dispatching events

To define an event, create a method on your component that returns your event payload and decorate it with Event like so:
1
import { WebComponent, Event } from '@webcomp/core';
2
3
class ThemeSelectButton extends WebComponent {
4
@Event('THEME_CHANGED')
5
changeTheme() {
6
// ...Optionally do stuff
7
return this.state.theme;
8
}
9
10
render() {
11
return <button class="theme-btn" onClick={this.changeTheme}>Like</button>
12
}
13
}
Copied!
Alternatively, instead of the decorator, you can use trigger method, available on every component:
1
import { WebComponent } from '@webcomp/core';
2
3
class ThemeSelectButton extends WebComponent {
4
changeTheme = () => {
5
// ...Optionally do stuff
6
this.trigger('THEME_CHANGE', this.state.theme);
7
}
8
9
render() {
10
return <button class="theme-btn" onClick={this.changeTheme}>Like</button>
11
}
12
}
Copied!

Listening to events

Every component has a .on method for subscribing to events. To listen to an event, you can do the following:
1
import { WebComponent } from '@webcomp/core';
2
3
class ThemedElement extends WebComponent {
4
componentDidMount() {
5
this.on('THEME_CHANGED', this.handleEvent); // Handlers are autobound
6
}
7
8
handleEvent(payload) {
9
this.setState({
10
selectedTheme: payload
11
});
12
}
13
14
render() {
15
return <div class={this.state.selectedTheme}>...</div>
16
}
17
}
Copied!

Unwrapping promises

When dispatching events, you can pass a promise as event payload. WebComp will wait for the promise to resolve and dispatch the event with the result of that promise as a payload. This works with both @Event decorator and this.trigger. I.e:
1
import { WebComponent } from '@webcomp/core';
2
3
class MyElement extends WebComponent {
4
componentDidMount() {
5
this.on('GET_DATA', this.handleEvent);
6
}
7
8
handleData = ({ data }) => {
9
this.setState({ data });
10
}
11
12
getData = async () => {
13
const res = await fetch('/api/user/profile')
14
this.trigger(res.json());
15
}
16
17
render() {
18
return (
19
<div>
20
<button onClick={this.getData}>Get Data</button>
21
</div>
22
)
23
}
24
}
Copied!
Last modified 2yr ago