I've been looking at many two-way data binding libraries and so far haven't found one that will fire onchange events when the input's value is set from a change on the model. Is there any way to do that with ractive.js?
It's possible, but is a little bit hacky. Browsers only fire the change
event as a result of user interaction (rather than input.value = 'someNewValue'
), so you have to watch the model and fire the event yourself:
var ractive = new Ractive({
el: 'main',
template: '#template',
data: { name: 'world' },
twoway: false
});
ractive.observe( 'name', function () {
// name has changed, need to simulate an event
var event = new Event( 'change' );
ractive.find( 'input' ).dispatchEvent( event );
});
ractive.find( 'input' ).addEventListener( 'change', function ( event ) {
console.log( 'event was fired', event );
});
// check the console!
ractive.set( 'name', 'everybody' );
<script src="http://cdn.ractivejs.org/latest/ractive.js"></script>
<main></main>
<script id='template' type='text/ractive'>
<h1>Hello {{name}}!</h1>
<input value='{{name}}'/>
</script>
Note that twoway binding has been disabled, otherwise you'd get extra events firing all over the place when the user did interact with the input - so you would need to listen for input
/change
events and handle those interactions yourself.