App.js
export class App { constructor() { this.widgets = [{ name: 'zero'}, {name: 'one'}, {name:'two'}]; this.shipment = { widget: this.widgets[1] }; } }App.html
<template> <require from="./widget-picker"></require> <require from="./some-other-component"></require> <widget-picker widget.bind="shipment.widget" widgets.bind="widgets"></widget-picker> <some-other-component widget.bind="shipment.widget"/> </template>widget-picker.js
import {bindable, bindingMode} from 'aurelia-framework'; export class WidgetPicker { @bindable({ defaultBindingMode: bindingMode.twoWay, changeHandler: 'widgetChanged' }) widget; @bindable widgets; widgetChanged(widget) { // Use an Event Aggregator to send a message to SomeOtherComponent // to say that they should check their widget binding for updates. } }widget-picker.html
<select value.bind="widget"> <option repeat.for="widget of widgets" model.bind="widget">${widget.name}</option> </select>问题:
@bindable 的 changeHandler 在绑定更新到 App.js 及其 this.shipment.widget 之前触发 widgetChanged 事件.
The Problem:
The @bindable's changeHandler fires the widgetChanged event before the binding gets updated to App.js and its this.shipment.widget.
所以当 Event Aggregator 消息出去时,之前的值仍然设置在 `this.shipment.widget' 上.
So when the Event Aggregator message goes out, the previous value is still set on `this.shipment.widget'.
有没有办法让 @bindable 的 changeHandler 等到所有要为 @bindable 更新的绑定完成?
Is there a way to make @bindable's changeHandler wait until all the bindings that will be updated for @bindable are done?
或者我可以使用另一个回调吗?也许是一个 changedHandler(过去时)?
Or is there another callback I can use? Maybe a changedHandler (past tense)?
我确实尝试将 change.delegate="widgetChanged" 添加到 select 中,希望 delegate 选项会使其变慢,但它仍然会在更新完全推出之前触发.
I did try to add change.delegate="widgetChanged" to the select, hoping that the delegate option would make it slower, but it still fires before the update is fully rolled out.
推荐答案你可以将需要做的工作推送到微任务队列中:
You could push the work you need to do onto the micro task queue:
import {bindable, bindingMode, inject, TaskQueue} from 'aurelia-framework'; @inject(TaskQueue) export class WidgetPicker { @bindable({ defaultBindingMode: bindingMode.twoWay, changeHandler: 'widgetChanged' }) widget; @bindable widgets; constructor(taskQueue) { this.taskQueue = taskQueue; } widgetChanged(widget) { this.taskQueue.queueMicroTask( () => { // Use an Event Aggregator to send a message to SomeOtherComponent // to say that they should check their widget binding for updates. }); } }这将确保它发生在事件循环的同一个回合"期间(而不是像 setTimeout(...) 那样做).
This will ensure it occurs during the same "turn" of the event loop (as opposed to doing something like setTimeout(...)).
更多推荐
@bindable changeHandler 在绑定完成更新之前触发
发布评论