Reputation: 323
I'm having trouble with the syntax for capturing an event then calling a local method. I've tried using arrow syntax, binding to 'this', and setting 'self' to 'this', but no matter what I do, I cannot invoke this.notify(...) from an event. I get the error "this.notify is not a function." Which undoubtably means I can't cross some set of contexts?
The notify functionality works fine otherwise, in all sorts of conditions, EXCEPT when I try to invoke it from an event.
Nothing magic here. app.js loads bus(an event bus), vuex/store, and Notifications, then app.vue.
So I'm sending events thru the store, and in this case must get an unrelated component to call a mutation in the store, and the store then to run a function in another unrelated component that displays a notification. Help appreciated. -Thanks.
App.js
(...)
import Notifications from 'vue-notification';
import velocity from 'velocity-animate';
Vue.use(Notifications, { velocity });
import app from "./app.vue";
const app = new Vue({
el: '#app',
store,
Notifications,
app,
render: h => h(app)
});
(...)
Component A - works just fine.
(...)
<b-btn v-on:click="$parent.showPokeNotice('display this nonsense text')"> My Arbitrary Text </b-btn>
(...)
Component B - but when I route thru the Store(Vuex) using an event, the context isn't the same. And so the $notify() and this.notify() aren't available.
<template>
(...)
<notifications
group="workspace"
position="top center"
width="40%">
</notifications>
(...)
</template>
(...)
mounted: function() {
(...)
/* Register Listeners for the Notification alerts */
var self = this;
Bus.$on('showPokeNotice', function (noticeText) {
self.showPokeNotice(noticeText);
});
},
(...)
methods: {
(...)
showPokeNotice : function (noticeText) {
this.notify({... params ...}); <---THIS IS THE PROBLEM CONTEXT
}
(...)
}
So, this.notify / ($notify) is within the Notifications component within Component B, but isnt' available from the event.
ERRORS:
[Vue warn]: Error in event handler for "showPokeNotice": "TypeError: Cannot read property 'showPokeNotice' of undefined"
(found in <Root>)
TypeError: Cannot read property 'showPokeNotice' of undefined ...
Thanks.
Upvotes: 2
Views: 847
Reputation: 323
ANSWER
So, while in context of the component, we use
this.notify({...
But, when responding to events, we use:
this.$notify({...
So, apparently there is some scope (context) loss when using events to call globals.
I hope this provides value to someone else.....
Upvotes: 1