【问题标题】:Update a binding in an Aurelia custom attribute更新 Aurelia 自定义属性中的绑定
【发布时间】:2016-06-08 17:13:54
【问题描述】:

代码:

my-view-model.html

<input on-scan.bind="onAirbillScanned" value.bind="airbill"/>

on-scan.ts

attached() {
    var scannerOptions = { onComplete: this.onScan.bind(this), preventDefault: true };
    (<any>$(this.element)).scannerDetection(scannerOptions);

    -- Code to add a signal to the value binding.
}

onScan(scannedValue, data) {
    if (typeof (this.value) == 'function') {

        let updatedScanValue = this.value(scannedValue);
        if (updatedScanValue !== undefined)
            this.element.value = updatedScanValue;
        else
            this.element.value = scannedValue;

       -- Code to Call the Signal

    }
}

问题:

我有一个自定义属性,允许我检测扫描、修改扫描输入的数据并将其设置为输入元素的值。

但是,我需要使用更新后的值更新 aurelia。

我可以触发一个“输入”事件来实现这一点。但是我发现了触发随机“输入”事件时的副作用。

我宁愿使用这里列出的信号系统:http://aurelia.io/docs.html#/aurelia/binding/1.0.0-beta.1.1.3/doc/article/binding-binding-behaviors

但问题是我需要信号在value.bind 绑定上。

问题:

有没有办法(使用我对绑定打开的element 的访问)来更新value.binding 以获得我可以调用以更新绑定的信号?

基本上我正在寻找这样的东西:

addSignal(element, property, signal) {...}

..

addSignal(this.element, 'value', 'scanFinished');

它会将输入的值绑定更新为如下所示:

<input on-scan.bind="onAirbillScanned" value.bind="airbill & signal: 'scanFinished'"/>

但不仅仅是重写 html,它还必须更新 Aurelia 以了解信号。

或者是否存在 Aurelia 为此类场景添加到所有绑定的信号值?

注意:如果所有 aurelia 绑定都定义了 AureliaBinding 信号,那么您就可以定位该控件并发送一个除了更新绑定之外没有副作用的事件。

【问题讨论】:

    标签: javascript aurelia


    【解决方案1】:

    我认为您遇到了麻烦,因为您正处于从自定义属性切换到使用自定义元素的方法的临界点。

    您可以通过执行以下操作来规避整个问题:

    scanner.html

    <template>
      <input ref="input" value.bind="value">
    </template>
    

    scanner.js

    import {bindingMode} from 'aurelia-framework';
    
    export class Scanner {
      @bindable({ defaultBindingMode: bindingMode.twoWay }) value;
      @bindable scanModifier = x => x;
      input: HTMLInputElement;
    
      attached() {
        let scannerOptions = {
          onComplete: value => this.value = this.scanModifier(value),
          preventDefault: true
        };
        (<any>$(this.input)).scannerDetection(scannerOptions);
      }
    
      detached() {
        (<any>$(this.input)).scannerDetection('destroy');
      }
    }
    

    用法:

    <require from="./scanner"></require>
    
    <scanner value.bind="airbill" scan-modifier.call="onAirbillScanned($event)"></scanner>
    

    这仍然可以使用自定义属性来完成,但对我来说这样更自然。你怎么看?

    【讨论】:

    • 这是有道理的。感谢您的回复。
    猜你喜欢
    • 1970-01-01
    • 2016-06-10
    • 2020-10-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多