简体   繁体   English

如何更新 aurealia 中的 observable

[英]How to update an observable in aurealia

I Am converting a project from Durandal to Aurelia and previously I have used an observable to limit the length of an input to 1 (and the last digit entered)我正在将一个项目从 Durandal 转换为 Aurelia,之前我使用 observable 将输入的长度限制为 1(以及输入的最后一个数字)

This is what I have:这就是我所拥有的:

HTML HTML

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

JavaScript: 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);
        }
    }
}


The otpaValueChanged function fires when the input changes however when length is > 1 I get the error "cannot read property 'opta' of undefined". otpaValueChanged function 在输入更改时触发,但是当长度> 1 时出现错误“无法读取未定义的属性‘opta’”。

I realise that "this" is undefined, but what I am not sure is how can I gain access to opta in this function?我意识到“这个”是未定义的,但我不确定如何在这个 function 中访问 opta?

Alternatively is there another way to approach this?或者有另一种方法来解决这个问题吗?

Thanks in advance!提前致谢!

You may need to bind your subscription to this like below:您可能需要将您的订阅绑定到此,如下所示:

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

  return true;
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM