WoJ
WoJ

Reputation: 29957

Why is the this.$on() callback triggered upon mount of a component?

I have a component which $emit to its parent upon some activity.

The parent listens to this event and triggers a function upon reception. This is assembled in mount():

<template>
    <v-app>
        <v-toolbar fixed app>
            <v-toolbar-title v-text="title"></v-toolbar-title>
            <v-spacer></v-spacer>
            <v-btn color="error" dark large>Large Button</v-btn>
        </v-toolbar>
        <v-content>
            <new-case v-on:dirty="updateDirty"></new-case>
        </v-content>
        <v-footer app>
            <span>&copy; 2017</span> dirty: {{dirty}}
        </v-footer>
    </v-app>
</template>

<script>
    export default {
        data() {
            return {
                case: {
                    id: null,
                    title: null,
                },
                cases: [],
                title: 'Vuetify.js',
                dirty: false,
            }
        },
        watch: {
            dirty: () => {
                console.log('requesting relaod of data')
            }
        },
        methods: {
            updateDirty(what) {
                console.log('requesting update of dirty state '+what)
                this.dirty = what
            }
        },
        mounted() {
            this.$on('dirty', this.updateDirty())
        }
    }
</script>

The whole mechanism works fine (the emmited even is correctly handled by the parent), except that when the component is mounted, I see in the console

17:36:01.380 App.vue?ea99:36 requesting update of dirty state undefined
17:36:01.449 App.vue?ea99:31 requesting relaod of data
17:36:01.561 backend.js:1  vue-devtools  Detected Vue v2.5.13 

Why is this.updateDirty() triggered upon the mount of the component? (even though nothing was emitted yet - not only the component which would emit something is not used yet, but the DevTools Vue panel does not show any events yet)

Upvotes: 0

Views: 210

Answers (1)

Justin MacArthur
Justin MacArthur

Reputation: 4050

The issue is with you $on call itself. The parenthesis after updateDirty, this.$on('dirty', this.updateDirty()), is the culprit, it is telling JS to run the function and store the result as the event handler. Try this.$on('dirty', this.updateDirty) instead so you're passing the reference to the function not the result.

Upvotes: 3

Related Questions