Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Having onchange event fire when input value set from data

Tags:

ractivejs

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?

like image 376
GreginNS Avatar asked Jul 31 '26 10:07

GreginNS


1 Answers

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.

like image 100
Rich Harris Avatar answered Aug 03 '26 11:08

Rich Harris



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!