Event Handling - View Working Example
Element events can be handled in the model by returning the handler function from a context function. This is a function returned by a function. For example, (context) => (event) => { // handle event }. The outer function provides access to the context, including the model object and element. The inner function is the event handler.
Clicking a Button
The following example shows an alert when the button is clicked.
HTML
<button id="mybutton" {}="onclick:onClickButton">Click Me</button>
Javascript
let buttonModel = {
onClickButton: () => () => alert('You clicked the button')
};
_M_.fill(document.getElementById('mybutton'), buttonModel);
Display Number of Times Clicked
The following example displays the number of times the button was clicked.
HTML
<div id="TimesClicked">
<button {}="onclick:onClickButton">Click Me</button>
<div>
You clicked the button <span {}="clickCount"></span> times.
</div>
</div>
Javascript
let clickModel = {
clickCount: 0,
onClickButton: (ctx) => (event) => ctx.root.clickCount++
};
_M_.fill(document.getElementById('TimesClicked'), clickModel);
Modified HTML
<div id="TimesClicked">
<button {}="onclick:onClickButton">Click Me</button>
<div>
You clicked the button <span {}="clickCount">3</span> times.
</div>
</div>