How to set up a checkbox binding in Aurelia

2019-06-15 18:31发布

问题:

I have a checkbox list, when the user checks one of the checkbox a function is called in the .js file and it in turn calls a method dataservice.js which calls a webapi controller, this all works fine and returns the correct data.

What happens when the process is finished is that the checkbox that fired the sequence isn't checked. I've inspected the result and schoolDistrict.IsChecked for that item is set to true, which is correct.

How do I get the checkbox to be checked?

Below is the code, but I am unsure about the check.one-way bind

<li repeat.for="schoolDistrict of schools.Districts">                                     
  <input type="checkbox" checked.one-way="schoolDistrict.IsChecked" value="${schoolDistrict.Value}" click.trigger="searchSchoolDistrict()"/>${schoolDistrict.Name}
</li>

Any help would be very much appreciated.

回答1:

There are a few issues here:

  • The problem is probably that your searchSchoolDistrict() code is changing the IsChecked property, but the one-way binding isn't listening for the change.
  • While interpolating the value would work, using the binding syntax is probably better style.
  • Setting up a change.delegate is more robust, and will listen to all changes on the checkbox, which is a best practice for checkboxes.
  • Deprecated Make sure you select the proper scope for searchSchoolDistrict(), as it probably lives on the $parent and not schoolDistrict.

Try using this instead:

<li repeat.for="schoolDistrict of schools.Districts">                                     
  <input type="checkbox" 
    checked.bind="schoolDistrict.IsChecked" 
    value.one-way="schoolDistrict.Value"
    change.delegate="searchSchoolDistrict()"/>
  ${schoolDistrict.Name}
</li>