Search code examples
ractivejs

How to trigger recomputation of computed property by DOM manipulation


In my test suite I'd like to confirm the effect of entering a character into a text input field. It should result in the change of a computed value.

It is, in fact, working correctly and recomputing when I type characters into the text field.

If I set the text field using

$('#my_input_field').val("F")

the computed value is not changed. Nor does it change if I trigger a keydown or keyup event on the input element. How can the property recomputation be triggered programmatically through DOM manipulation?


Solution

  • You can use ractive.updateModel(keypath) to force two-way bindings to update:

    <input value='{{value}}'/>
    
    ractive.find('input').value = 'newValue';
    ractive.updateModel('value'); // or just `ractive.updateModel()`
    console.log( ractive.get( 'value' ) ); // 'newValue'
    

    If you want to cause the update by triggering artificial DOM events, use the change event, because that's what the two-way binding is listening for (rather than keydown and friends). It has to be a native DOM event, not a jQuery event (which uses a different mechanism) – the Ractive test suite uses simulant to make this a bit less of a hassle.