'这'在拦截绑定行为期间不引用当前对象上下文

时间:2018-06-03 17:11:12

标签: javascript aurelia aurelia-binding

在Aurelia应用程序中,我正在使用绑定行为。它看起来像这样:

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

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

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

这就是绑定行为的样子:

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;
    }
}
}

如何解决此问题?

2 个答案:

答案 0 :(得分:1)

与我的评论相关,作为快速和彻底的修复,我会尝试将类和方法分别作为参数传递。我测试了它,它确实有效。但也许一些aurelia专家知道如何处理这个问题的更好方法:

<强> HTML

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

<强> InterceptBindingBehavior.ts

export class InterceptBindingBehavior {
readonly interceptMethods = ['updateTarget', 'updateSource', 'callSource'];

bind(binding, scope, interceptorClass, interceptorMethod) {
    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] = interceptorClass[interceptorMethod].bind(interceptorClass, 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;
    }
}

答案 1 :(得分:1)

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

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

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

在组件的构造函数

export class YourComponent {
  constructor(...) {
    // guess you have this.controller = controller; somewhere

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

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

export class Controller {
  constructor(...) {
    this.saveChange = this.saveChange.bind(this);
  }
}