0
methods:{
    setSwiper() {
        const test = new something;
        test.customEvent('changeEvent', this.handleChange);
    },
    handleChange(){
        console.log(this)// vue instance
    }
}

here in method handleChange() I want to access "this" from event

methods:{
    setSwiper() {
        const test = new something;
        test.customEvent('changeEvent', function(){
        console.log(this); // event
    });
    }
}

is there any possible way to access event from this in vue method? like using bind, apply ...

gdev219
  • 3
  • 2
  • *access event from this* what did you want `this` to be exactly? what does the function `customEvent` do? you can bind whatever you want `this` to be in here in line 6 `});` ...e.g. `}.bind(whatever));` – Jaromanda X Feb 06 '20 at 04:15
  • @JaromandaX at the first code is there possible to access event this in handleChange method? something like test.customEvent('changeEvent', this.handleChange.bind(this)); – gdev219 Feb 06 '20 at 04:26
  • The answer likely depends on how `customEvent()` invokes the event handler. Can you show that in the question? – tony19 Feb 06 '20 at 04:39
  • oh, looks like you want an arrow function for the callback - or as I said already ... `function(){ console.log(this); }.bind(this)` – Jaromanda X Feb 06 '20 at 04:41
  • This is very specific to `something`. Please, specify the exact library, this will make the question more specific and help other users who use the same library. Possible duplicate of https://stackoverflow.com/questions/58600586/this-direction-in-vue-typescript-vue-awesome-swiper – Estus Flask Feb 06 '20 at 08:21

1 Answers1

0

As shown in this similar Vue question, this is a common problem with legacy libraries that use dynamic this context instead of arguments to supply data to callback functions.

Whenever possible, try to use arguments, some libraries promote the use of this but also provide necessary data as arguments:

test.customEvent('changeEvent', e => {
  console.log(e); // possibly an event
  console.log(this); // vue instance
});

If this is not the case, self = this hack can be used:

const self = this;

test.customEvent('changeEvent', function () {
  console.log(this); // event
  console.log(self); // vue instance
});

A workaround that is compatible with Vue methods that are pre-bound to Vue instance is the use of helper function that passes dynamic context as an argument:

function contextWrapper(fn) {
    const self = this; // doesn't matter if used solely with Vue methods

    return function (...args) {
        return fn.call(self, this, ...args);
    }
}

...

setSwiper() {
    const test = new something;
    test.customEvent('changeEvent', contextWrapper(this.handleChange));
},
handleChange(e){
    console.log(e); // event
    console.log(this); // vue instance
}
Estus Flask
  • 206,104
  • 70
  • 425
  • 565