2

So i'm building a chat room module into my laravel app with vue,echo and pusher. The real-time broadcasting and receiving with laravel works already, the issue i'm having is when i call a method of the vue instance from the echo subscribe function i get a method undefined error in java-script. Please note i am a noob in vue.js Here is my app.js file of laravel

Vue.component('example', require('./components/Example.vue'));
Vue.component('chat-messages', require('./components/ChatMessages.vue'));

window.App = {};
window.App.app = 'hello';

window.App.app = new Vue({
    el: '#wrapper',
    data: {
        messages: [],
        rooms: [],
        test: 'yes',
        first: 0
    },
    created() {
        this.fetchRooms();
    },
    methods: {
        fetchMessages(id) {
            axios.get('/messages/' + id).then(response => {
                this.messages = response.data;
                console.log(response.data);
            });
        },
        fetchRooms()
        {
            axios.get('/rooms').then(response => {
                this.rooms = response.data;
                this.first = this.rooms[0].id;
                this.fetchMessages(this.first);
                this.subscribeRoom();
            });
        },  
        sendMessage(data)
        {
            axios.post('/chat/send', {
                message: data.message,
                room_id: data.room_id
            }).then(response => {
                this.messages.push(response.data);
            });
        },
        subscribeRoom()
        {
            console.log('sub');
            this.rooms.forEach(function(entry)
            {
                Echo.private('chat.'+entry.id)
                        .listen('.newMessage',(e)=>{
                            this.updateMessage(e.message); //throws undefined error when a new message comes in also when i try to push directly says undefined variable for this.messages
                            console.log(e);
                });
            });
        },
        updateMessage(message)
        {
            this.messages.push(message);
        }
    }
});  

1 Answer 1

1

You used a fat arrow function for your callbacks everywhere except that one, so you lost the correct context on this. Change it to

subscribeRoom()
{
    this.rooms.forEach(entry => {
        Echo.private('chat.'+entry.id)
            .listen('.newMessage', e => this.updateMessage(e.message)); 
    });
},
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.