首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >自身属性上的Aurelia更改不调用更改的侦听器

问自身属性上的Aurelia更改不调用更改的侦听器
EN

Stack Overflow用户
提问于 2018-12-17 20:01:15
回答 1查看 241关注 0票数 1

我正在用aurelia编写一个自定义属性,在我的attribute类中,我有一个名为'visibility‘的可绑定属性。然后从外部(父组件)绑定到此属性并更改该组件上的值,激发visibilityChanged,但在我的属性类中,当我更改该值时,不会调用visibilityChanged方法。

例如:

代码语言:javascript
复制
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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-12-18 12:51:00

我找到了答案,并把它写在这里。问题是上下文被改变,而不是改变事件的传播。

我将_onElementFocused设置为元素焦点事件的侦听器,并传递函数,而不是使用箭头函数或其他函数。请看以下内容:

代码语言:javascript
复制
  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属性,而不是视图模型(自定义属性类)的属性。所以我把它的调用改为箭头函数类型,现在一切都正常了。如下所示:

代码语言:javascript
复制
  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.

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53814828

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档