Event Handling

Cross-component communication

Components should never directly depend on each others. Component A should never include component B and fire it’s methods directly. All the communication and synchronisation between components should be done using Events. Strudel implements a simple class responsible for controlling event communication - EventEmitter.

Events

EventEmitter is automatically included as a mixin for every component, which means by default every component is able to use event communication.

Key methods responsible for handling communication are:

Full Event specification can be found in the API

Example below shows cross-component event communication.

<div class="subscriber"></div>
<button class="publisher" data-id="0">0</button>
@Component('.subscriber')
class Subscriber {
init() {
this.$on('publisher:publish', (id) => { // Attaching listener
this.$element.html(`${id}`);
});
}
}
@Component('.publisher')
class Publisher {
@Evt('click')
publish() {
this.$emit('publisher:publish', this.$data.id); // Firing event
}
}

Using EventEmitter

Static classes introduced for handling utility configuration or data requesting can also communicate with components using events. To use events simply include EventEmitter class into your static class and suddenly it will be able to communicate with components.

import { EventEmitter } from 'strudel';
const vent = new EventEmitter();
class DataProvider {
constructor(url) {
fetch(url).then((resp) => {
vent.emit('data:fetched', resp.json());
});
}
}