You can add event listener directly on node by getting node reference with querySelector method of view instance.
import Monkberry from 'monkberry';
import Template from './monkberry.monk';
const view = Monkberry.render(Template, document.body);
const node = view.querySelector('div');
node.addEventListener('click', (event) => { ... });
But this can be difficult when using ifs and for, because nodes can appear and disappear from view.
Better solution is using event delegating, install monkberry-events:
npm install monkberry-events --save
and import it once in your project. It will add two more methods on Monkberry instances: on
and off
.
import 'monkberry-events';
Now you can add event listener like this:
view.on('click', 'div', (event) => { ... });
Also there is another aproach using directives.
<div :onclick={{ this.handleClick }}>
...
</div>
See all available event listeners in monkberry-directives package.
Next, we describe how to use the component approach in Monkberry.