Method calls
edit this pageSee also: proxy events
As an alternative to proxy events, you can call any method of your Ractive instance, in response to an event directive, right from your template:
<p>foo is {{foo}}</p>
<button on-click='toggle("foo")'>toggle foo</button>
In this case, because ractive.toggle() is a built-in method, clicking the button will toggle the value of foo
between true
and false
(demo).
This also works with custom methods:
var ractive = new Ractive({
el: 'body',
template: '<button on-click="klaxon()">sound the klaxon</button>',
audio: new Audio( 'klaxon.mp3' ),
klaxon: function () {
this.audio.play();
}
});
You can pass as many arguments to the method as you like, including data references:
{{#each items :i}}
<button on-click='select(this,i)'>select this item</button>
{{/each}}
Notice that mustaches are not used with data reference in method calls, i.e. {{i}}
and will cause errors if they are. String literals need to be in quotes:
<button on-click='set( "foo", true)'>make foo true</button>
You can also pass the event
object, or properties thereof (event.original
is the original DOM event) (demo):
<div
on-mousemove='set({
x: event.original.clientX,
y: event.original.clientY
})'
on-mouseleave='set({
x: "unknown",
y: "unknown"
})'
>
<p>current mouse position: {{x}} x {{y}}</p>
</div>