Binding to select element change event - delay in updated selected value

I have the following:

const list = {
    selected: null,
    options: [ 
         {name: 'option 1'},
         {name: 'option 2'}
    ]
}

list.selected = list.options[1]
<select change.trigger="onChange(list.selected)" value.bind="list.selected">
    <option repeat.for="entry of list.options" model.bind="entry">
            ${entry.name}
    </option>
</select>
onChange(selected) {
     console.log(selected)
}

When the onChange event fires, it prints out the selected value. Problem is, that is prints out the previously selected value.

I need to add in

setTimeout( () => {
      console.log(selected)
}, 100)

To make it print the correct selected value. Anyone else notice this?

Thas is because aurelia’s binding system kicks in as a micro-task. (at least in AU1).
so when you attached a handler to the change event , your code runs before the binding is propogated.

you don’t have to wait 100ms, you can queue your code using the TaskQueue as a microtask and that should also do the trick.
(an easy way to verify that, would be to pass 0ms to the setTimeout - that causes your code to run on the next Task - and that should be enough for aurelia binding system to be done.).

BTW: the appropiate way to listen on change when you use an MVVM pattern, is to listen on the value in the VM, rather then to hook directly on the DOM.

2 Likes

Super. Thanks for the info :smiley: