cklmercer/vue-events

How should I use it in a .js file?

Closed this issue · 3 comments

aisin commented

Hi @cklmercer , thanks for your code, and I have an issue about using the plugin.
In component A:

mounted () {
  this.$events.on('sucess', this.eventData);
}

in component B:

import { doSomething } from './foo.js';
export default {
  created () {
    doSomething();
  }
};

and in foo.js file:

export function doSomething () {
  // some code
  this.$events.emit('sucess', data);
}

or in foo.js file:

import Vue from 'vue';
export function doSomething () {
  // some code
  Vue.$events.emit('sucess', data);
}

while running this project, there will be an error Uncaught TypeError: Cannot read property 'emit' of undefined.
so how should I use it in foo.js file currently?

The issue you're running into looks like a scoping issue. this isn't the same in each of your contexts. You could probably used a computed property in Component B and bind this to doSomething

@cklmercer is right, the this inside the doSomething function is not bound to anything. Try calling doSomething.call(this) instead of doSomething(), to pass the Vue instance as the context for the doSomething function

aisin commented

I solved it, thanks for your reply. @cklmercer @christophemarois