【问题标题】:@bindable changeHandler fires before bindings are done updating@bindable changeHandler 在绑定完成更新之前触发
【发布时间】:2016-06-05 20:24:36
【问题描述】:

代码:

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

所以当事件聚合器消息发出时,之前的值仍然设置在 `this.shipment.widget' 上。

问题:

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

或者我可以使用其他回调吗?也许是 changedHandler(过去时)?

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

【问题讨论】:

    标签: javascript aurelia


    【解决方案1】:

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

    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(...) 这样的事情)。

    【讨论】:

    • 这很完美!非常非常感谢你。我喜欢 Aurelia 的绑定系统。
    • 这仍然是@JeremyDanyow 的最佳方法吗?谢谢!
    猜你喜欢
    • 2017-12-10
    • 1970-01-01
    • 2016-11-20
    • 1970-01-01
    • 2022-12-05
    • 2011-06-03
    • 2017-10-06
    • 2014-11-01
    • 1970-01-01
    相关资源
    最近更新 更多