我正在用aurelia编写一个自定义属性,在我的attribute类中,我有一个名为'visibility‘的可绑定属性。然后从外部(父组件)绑定到此属性并更改该组件上的值,激发visibilityChanged,但在我的属性类中,当我更改该值时,不会调用visibilityChanged方法。
例如:
export class PaOnScreenKeyboardCustomAttribute {
@bindable visibility = false;
visibilityChanged(newValue, oldValue) {
console.log('change visibility');
if (this.keyboardElement) {
this.keyboardElement.style.display = newValue ? 'initial' : 'none';
}
}
_onElementFocused(event) {
// let htmlElement = this; // use this if needed
this.visibility = true;
console.log('show');
}
_onElementDefocused(event) {
// let htmlElement = this; // use this if needed
this.visibility = false;
console.log('hide');
}
}我应该如何更改类中的属性值,以便更改调用visibilityChanged
发布于 2018-12-18 12:51:00
我找到了答案,并把它写在这里。问题是上下文被改变,而不是改变事件的传播。
我将_onElementFocused设置为元素焦点事件的侦听器,并传递函数,而不是使用箭头函数或其他函数。请看以下内容:
showOnFocusChanged(newValue, oldValue) {
if (newValue === true || newValue === 'true') {
this.element.addEventListener('focus', this._onElementFocused);
this.element.addEventListener('focusout', this._onElementDefocused);
} else {
this.element.removeEventListener('focus', this._onElementFocused);
this.element.removeEventListener('focusout', this._onElementDefocused);
}
}这样,在_onElementFocused函数中,this引用调用事件的元素。因此,this.visibility = true;更改了该元素的visibility属性,而不是视图模型(自定义属性类)的属性。所以我把它的调用改为箭头函数类型,现在一切都正常了。如下所示:
showOnFocusChanged(newValue, oldValue) {
if (newValue === true || newValue === 'true') {
this.element.addEventListener('focus', (event) => this._onElementFocused(event));
this.element.addEventListener('focusout', (event) => this._onElementDefocused(event));
} else {
this.element.removeEventListener('focus', (event) => this._onElementFocused(event));
this.element.removeEventListener('focusout', (event) => this._onElementDefocused(event));
}
}可以看出,问题不是关于aurelia的,而是关于javascript上下文本身的,而是把我搞糊涂了。希望这对其他人有帮助。TG.
https://stackoverflow.com/questions/53814828
复制相似问题