简体   繁体   中英

Vuejs $emit doesn't fire on callback

In the following code:

export default {
    props: ['note'],
    methods: {
        remove(){
            NoteRepo.remove(this.note, (err) => {
                if (err) {
                    console.log('Should Fire')
                    this.$emit('alerted', {
                        type: 'error', 
                        message: 'Failed to remove note'
                    });
                }
            })
        }
    }
}

When the remove function gets called, the console logs "Should Fire" but the $emit event doesn't get fired. If I move the $emit outside of the callback like so:

export default {
    props: ['note'],
    methods: {
        remove(){
            this.$emit('alerted', {
                type: 'error', 
                message: 'Failed to remove note'
            });

            NoteRepo.remove(this.note, (err) => {
                if (err) {
                    console.log('Should Fire')
                }
            })
        }
    }
}

It works. I've tried assigning _this = this and using that to fire the $emit but no difference.

Why does the $emit event not fire in a callback?

So it turns out it was something in NoteRepo causing the problem. Specifically the firebase event callback.

constructor () {
        super();

        // Initialize Firebase
        Firebase.initializeApp({
            apiKey: "xxx",
            authDomain: "xxx",
            databaseURL: "xxx",
            storageBucket: "xxx",
            messagingSenderId: "xxx"
        });

        this.ref = Firebase.database().ref('notes');
        this.attachFirebaseListeners();
    }

    attachFirebaseListeners() {
        this.ref.on('child_added', this.onAdded, this);
        this.ref.on('child_removed', this.onRemoved); // Removing 'this' here seems to of fixed it.
        this.ref.on('child_changed', this.onChanged, this);
    }

I'm not sure what exactly was wrong, but this seems to of sorted it for now.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM