Alex Alex - 1 month ago 11
Javascript Question

With minimal changes to the object structure, how can you reference a function from another function in the same object?

Using Javascript (ES6), I need to reference an handler function

onKeyup
so that I can add and remove an event listener in two functions declared in the same object.

Would you see how I can access that
onKeyup
function from the two
bind
and
unbind
functions in the object? :

export default {
bind(el) {
let privateVar = 42;

function foobar() {
console.log('Foobar hit', privateVar);
}

function onKeyup() {
console.log('onKeyup hit');
foobar();
}

el.addEventListener("keyup", onKeyup, false);
},

unbind(el) {
//`onKeyup` does not exist here, how can I fix that?
el.removeEventListener("keyup", onKeyup, false);
}
}


Is this possible?

My first thought would be to modify the code like that, but the result is in my opinion less readable :

export default {
privateVar : null,

onKeyup() {
console.log('onKeyup hit');
this.foobar();
},

foobar() {
console.log('Foobar hit', this.privateVar);
},

bind(el) {
this.privateVar = 42;
el.addEventListener("keyup", this.onKeyup, false);
},

unbind(el) {
el.removeEventListener("keyup", this.onKeyup, false);
}
}


Would you have a better, cleaner way to do that?

Note : I cannot change the structure of the
bind
and
unbind
functions in that object since it is used as a directive declaration for Vue.js 2.*.

EDIT:

I also tried a second way of organizing my code :

export default {
onKeyup : null,

bind(el) {
let privateVar = 42;

function foobar() {
console.log('Foobar hit', privateVar);
}

this.onKeyup = function() {
console.log('onKeyup hit');
foobar();
};

el.addEventListener("keyup", this.onKeyup, false);
},

unbind(el) {
el.removeEventListener("keyup", this.onKeyup, false);
}
}


...but then I see this error message :
Uncaught TypeError: Cannot set property 'onKeyup' of undefined

Answer

You should be able to use an IIFE to encapsulate everything and only expose the bind() and unbind() functions.

export default (function() {
    var privateVar;

    function onKeyup() {
        console.log('onKeyup hit');
        foobar();
    }

    function foobar() {
        console.log('Foobar hit', privateVar);
    }

    function _bind(el) {
        privateVar = 42;
        el.addEventListener("keyup", onKeyup, false);
    }

    function _unbind(el) {
        el.removeEventListener("keyup", onKeyup, false);
    }

    return {
        bind:_bind,
        unbind:_unbind
    };
})();