【问题标题】:How to update an observable in aurealia如何更新 aurelia 中的 observable
【发布时间】:2021-07-12 04:15:37
【问题描述】:

我正在将一个项目从 Durandal 转换为 Aurelia,之前我使用一个 observable 将输入的长度限制为 1(以及输入的最后一个数字)

这就是我所拥有的:

HTML

<input autocomplete="off" type="number" class="otp" maxlength=1 id="otpa" value.bind="otpa.value" />

JavaScript:


'use-strict';

import { Router } from 'aurelia-router';
import { inject, BindingEngine } from 'aurelia-framework';

@inject(Router, BindingEngine)
export class Register {

    otpa = {
        value: '',
        hasFocus: false
    };

    constructor(router, bindingEngine) {
        this.router = router;
        this.bindingEngine = bindingEngine;
    }

    activate = () => {

        this.subscriptions = this.bindingEngine
            .propertyObserver(this.otpa, 'value')
            .subscribe(this.otpaValueChanged);

        return true;
    };

    deactivate = () => {

        this.subscriptions.dispose();

        return true;
    };

    otpaValueChanged(newValue, oldValue) {
        if (newValue.length > 1) {
            this.otpa.value = newValue.substring(newValue.length - 1, newValue.length);
        }
    }
}


当输入改变时 otpaValueChanged 函数触发,但是当长度大于 1 时,我收到错误“无法读取未定义的属性 'opta'”。

我意识到“this”是未定义的,但我不确定如何才能在此函数中访问 opta?

还有其他方法可以解决这个问题吗?

提前致谢!

【问题讨论】:

    标签: javascript aurelia


    【解决方案1】:

    您可能需要像下面这样绑定您的订阅:

    activate = () => {
      this.subscriptions = this.bindingEngine
          .propertyObserver(this.otpa, 'value')
          .subscribe(this.otpaValueChanged.bind(this));
    
      return true;
    };
    

    【讨论】:

      猜你喜欢
      • 2015-07-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-08
      相关资源
      最近更新 更多