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)
This is what I have:
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);
}
}
}
The otpaValueChanged function fires when the input changes however when length is > 1 I get the error "cannot read property 'opta' of undefined".
I realise that "this" is undefined, but what I am not sure is how can I gain access to opta in this function?
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;
};