首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >“‘this”在截获绑定行为期间不引用当前对象上下文

“‘this”在截获绑定行为期间不引用当前对象上下文
EN

Stack Overflow用户
提问于 2018-06-04 01:11:12
回答 1查看 44关注 0票数 0

在一个Aurelia应用程序中,我使用了绑定行为。它看起来是这样的:

<div id="slider" ej-slider="e-value.two-way:controller.item.progress & intercept:controller.saveChange;" ></div>

截取绑定行为from here是绑定controller.saveChange,它会被调用。

然而,问题是在该方法中,this引用的不是控制器,而是绑定。因此,我无法访问执行实际保存所需的控制器的方法和属性。

绑定行为如下所示:

代码语言:javascript
复制
export class InterceptBindingBehavior {

readonly interceptMethods = ['updateTarget', 'updateSource', 'callSource'];

bind(binding, scope, interceptor) {
    let i = this.interceptMethods.length;
    while (i--) {
        let method = this.interceptMethods[i];
        if (!binding[method]) {
            continue;
        }
        binding[`intercepted-${method}`] = binding[method];
        let update = binding[method].bind(binding);
        binding[method] = interceptor.bind(binding, method, update);
    }
}

unbind(binding, scope) {
    let i = this.interceptMethods.length;
    while (i--) {
        let method = this.interceptMethods[i];
        if (!binding[method]) {
            continue;
        }
        binding[method] = binding[`intercepted-${method}`];
        binding[`intercepted-${method}`] = null;
    }
}
}

我该如何解决这个问题?

EN

回答 1

Stack Overflow用户

发布于 2018-06-07 06:58:11

看起来原始的InterceptBindingBehavior只支持直接在当前绑定上的方法,它使用interceptor.bind(binding, ...来确保this被正确设置。

但是您希望thiscontroller,而不是当前绑定。

简单的解决方法是自己强制执行this

在组件的构造函数中

代码语言:javascript
复制
export class YourComponent {
  constructor(...) {
    // guess you have this.controller = controller; somewhere

    this.controller.saveChange = this.controller.saveChange.bind(this.controller);
  }
}

或者在控制器的构造函数中

代码语言:javascript
复制
export class Controller {
  constructor(...) {
    this.saveChange = this.saveChange.bind(this);
  }
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50668958

复制
相关文章

相似问题

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