Having an onchange event when an input value is set from data
Possibly, but a little hacky. Browsers only fire the event change
as a result of user interaction (not input.value = 'someNewValue'
), so you need to look at the model and fire that 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 the twoway binding is disabled, otherwise you will get additional events that will fire all over the place when the user interacts with the input - so you will need to listen for input
/ change
and handle those interactions.
source to share
The answer (for my purposes) is actually pretty simple. A bit of background first - which I probably should have laid out in the original question. Let's say you are viewing / editing a customer profile. Meanwhile, someone is doing the same. They update the phone # and save the profile. Without some special action, you won't see the new phone # unless you reload the profile. My goal is to make our data / forms "reactive". One of the difficulties was updating the form. This is simple enough by itself, but how to handle any onchange events on inputs. Let's say the country has changed, so a new list of regions should appear. Me, changing the country, will be fired by the country for the exchange event, and a new list will appear. If reactive changes happen and countries are updated, it won't fire. This is problem. Shortly speaking,the answer is that it doesn't have onchange events, but it does have a Ractive.on ('change') event, then parse the key path for something interesting. This will catch the changes from the person and change from "outside", either through a set or merge.
var cust = {
firstname: 'Fred',
lastname: 'Flintstone'
}
ractive = new Ractive({
el: '#spot',
template: '#tmpl1',
data: {customer: cust},
lazy: true
})
ractive.on('change', function(kp) {
console.log(kp)
})
setTimeout(function() {
ractive.set('customer.firstname', 'Wilma')
}, 2000)
setTimeout(function() {
ractive.merge('customer', {firstname: 'Barney', lastname: 'Rubble'})
}, 4000)
<script src="http://cdn.ractivejs.org/latest/ractive.js"></script>
<body>
<div id='spot'></div>
<script id='tmpl1' type='text/tmpl'>
<input value={{customer.firstname}}>
<input value={{customer.lastname}}>
</script>
</body>
source to share