@bindable changeHandler在绑定完成更新之前触发

时间:2016-02-23 20:00:27

标签: javascript aurelia aurelia-binding

代码:

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>

插件-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.
  }
}

插件-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事件。

因此,当Event Aggregator消息消失时,仍然会在`this.shipment.widget'上设置之前的值。

问题:

有没有办法让@bindable的changeHandler等到所有为@bindable更新的绑定都完成?

或者我可以使用另一个回调吗?也许是一个改变过的手(过去时)?

我确实尝试将change.delegate="widgetChanged"添加到select,希望delegate选项会使速度变慢,但在完全推出更新之前它仍然会触发。

1 个答案:

答案 0 :(得分:5)

您可以将需要完成的工作推送到微任务队列:

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(...)那样)。