问题
Right now we have the following code which fills kind of "dirty" with the power of aurelia bindings:
HTML
<input class="order-input-root" type="checkbox" click.delegate="checkAll()" />
Javascript
checkAll(){
if($("input:checkbox.order-input-root").is(":checked"))
{
$("input:checkbox.order-input").removeAttr("checked");
$("input:checkbox.order-input").click();
return true;
}else
{
$("input:checkbox.order-input").removeAttr("checked");
return true;
}
}
Is there any way to improve this, is there any built-in functionality on aurelia?, my concern is that if I want to have different lists on a single page this code is going to be a mess
回答1:
Assuming that all checkboxes are properly bound, you could easily achieve this by using the change
event.
JS:
export class Welcome {
constructor() {
this.isAllChecked = false;
this.items = [
{ display: 'test 1', checked: false },
{ display: 'test 2', checked: false },
{ display: 'test 3', checked: false },
{ display: 'test 4', checked: false },
];
}
checkAll() {
this.items.forEach(i => i.checked = this.isAllChecked);
}
}
HTML:
<template>
<label>
<input type="checkbox" value="true" checked.bind="isAllChecked" change.delegate="checkAll()" />
Check All
</label>
<label repeat.for="item of items" style="display: block">
<input type="checkbox" value="true" checked.bind="item.checked" />
${item.display}
</label>
</template>
Here is an example http://plnkr.co/edit/AzU1dtOVgRpkVUHvupcZ?p=preview
If for some reason the change
method is not enough, you could use the bindingEngine
to observe the checkbox. Like this:
JS:
import {BindingEngine} from 'aurelia-binding'; //or aurelia-framework
import {inject} from 'aurelia-dependency-injection'; //or aurelia-framework
@inject(BindingEngine)
export class Welcome {
constructor(bindingEngine) {
this.bindingEngine = bindingEngine;
this.checkAll = false;
this.items = [
{ display: 'test 1', checked: false },
{ display: 'test 2', checked: false },
{ display: 'test 3', checked: false },
{ display: 'test 4', checked: false },
];
this.checkAllSubscriber = this.bindingEngine.propertyObserver(this, 'checkAll')
.subscribe((newValue, oldValue) => {
this.items.forEach(i => i.checked = newValue);
});
}
detached() {
this.checkAllSubscriber.dispose();
}
}
HTML:
<template>
<label>
<input type="checkbox" value="true" checked.bind="checkAll" />
Check All
</label>
<label repeat.for="item of items" style="display: block">
<input type="checkbox" value="true" checked.bind="item.checked" />
${item.display}
</label>
</template>
Remember to call dispose()
when you no longer need it.
Here is a working example http://plnkr.co/edit/uWjIEN8ep184af3w5Ay9?p=preview
These are the solutions I have found. I will update this answer if I find another approach.
Hope this helps!
来源:https://stackoverflow.com/questions/36366297/check-all-option-on-aurelia-can-this-be-improved