To attach the event handler to an event use the event binding syntax (eventName)="statement". For example:
class EventHandling extends BaseComponent { public int $count = 0; ... <button (click)="$count = $count + 1">Add 1</button> <span>Count: <b>$count</b></span>
The result:
You can find the list of all available events at Event reference.
You can use component's method as an event handler:
class EventHandling extends BaseComponent { public string $greetingMessage = ''; function greet() { $this->greetingMessage = 'Hello Viewi!'; } ... <button (click)="greet()">Greet</button> <b>$greetingMessage</b>
The result:
You can also pass arguments into the method:
class EventHandling extends BaseComponent { public string $greetingMessage = ''; function greetByName($name) { $this->greetingMessage = "Hello $name!"; } ... <button (click)="greetByName('Viewi')">Greet Viewi</button> <button (click)="greetByName('Diana')">Greet Diana</button> <b>$greetingMessage</b>
The result:
Sometimes you also need to access the original DOM event in your statement. For that purpose use $event variable.
<form (submit)="handleSubmit($event)"> <button>Send</button> </form>
And now you can access it in your handleSubmit method:
use Viewi\DOM\Events\DOMEvent; class EventHandling extends BaseComponent { public function handleSubmit(DOMEvent $event) { $event->preventDefault(); ...
Please note: if you already have in your component property $event, then you will have to use $_component->event in order to use the template. $event is a magic variable that contains reference to the DOM event.
Well, if really don't know what event it will be, you can use a dynamic syntax: $myEventName="expression", where $myEventName should contain a valid event attribute name, like this:
public string $myEventName = '(click)';
Whenever you decide to change event name, the application will reattach events accordingly. You are allowed to change it to regular attribute name, that is also ok and application will remove the event and set attribute accordingly.