On-select event not being triggered with RactiveJS
-
21-12-2019 - |
Question
Am I doing something wrong?
My template
<select id="muni" class="form-control" value="{{formData.muni_ssn}}" on-select="muni_selected">
{{#formData.municipalities}}
<option value="{{ssn}}">{{name}}</option>
{{/formData.municipalities}}
</select>
My js code
var caseForm = new Ractive({
el: "case-form",
template: "#CaseFormTemplate",
data: {
formData: mappeal.caseFormData
}
});
caseForm.on("muni_selected", function (event) {
alert(event.context.formData.muni_ssn);
});
Solution
There's no such thing as the select
event. In standard JavaScript, without Ractive, you'd do this to listen to changes in the <select>
element's value:
// 'change' event, not 'select' event
document.getElementById( 'muni' ).addEventListener( 'change', function () {
console.log( 'select value changed to', this.value );
});
So the equivalent in Ractive would be
<select id="muni" class="form-control" value="{{formData.muni_ssn}}" on-change="muni_selected">
{{#formData.municipalities}}
<option value="{{ssn}}">{{name}}</option>
{{/formData.municipalities}}
</select>
But there's actually a slightly easier way to listen for those changes with Ractive - observe the data itself. First, we can get rid of the event handler directive:
<select id="muni" class="form-control" value="{{formData.muni_ssn}}">
{{#formData.municipalities}}
<option value="{{ssn}}">{{name}}</option>
{{/formData.municipalities}}
</select>
Then, in your code, do this:
caseForm.observe( 'formData.muni_ssn', function ( newValue, oldValue ) {
console.log( 'changed from', oldValue, 'to', newValue );
});
The advantage of doing it this way is that you don't need to distinguish between changes that happen as a result of DOM interaction, and changes that happen programmatically (e.g. as part of your initial setup) - making it much easier to keep track of application state.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow