Search code examples
javascriptaurelia

'this' does not reference current object context during intercept of Binding Behavior


In an Aurelia app, I am using a binding-behavior. It looks like this:

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

The intercept binding behavior from here is binding controller.saveChange which does get called.

However, the issue is that within that method, this refers not to the controller, but to the binding. So I can't access the methods and properties of the controller which are needed to do the actual save.

This is what the Binding Behavior Looks like:

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

How do I resolve this?


Solution

  • Related to my comment, as a quick&dirty fix I would try to pass the class and the method separately as arguments. I tested it and it does work. But maybe some aurelia experts know a better way how to handle this:

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