emit works too good



  • Hi

    For simplicity, I have 1 layout that at any given moment, contains one of 3 available pages, depends on the user flow. Each page has the following code

    created() {
       this.startEverything();
    },
    
    startEverything() {
       //call server to get data for this page
    },
    

    When a user is doing a certain action, I want to “refresh” ONLY the current page he is on. The action is done from the layout, so I did the following in the layout:

    this.$root.$emit('set-start-everything', true );
    

    And on each page I did the following

    mounted() {
       this.$root.$on('set-start-everything',this.startEverything);
    },
    

    I was hoping that once the user is doing action X (on the layout), the layout will call ONLY the relevant startEverything code, based on the current/active page he is on.

    Apparently I was wrong, it seems that emit is calling ALL available startEverything on all the pages, some of them it even called twice and more (not sure why).

    I thought of changing each page’s startEverything method to a more unique name but my purpose was to reload the page “blindly”, no matter the page he is on and making such change will prevent me from doing that.

    Any idea how can I implement this scenario without waking everybody up?
    Thanks



  • My 2c,

    Use vuex, store the state you want to modify, watch it somewhere.
    When you catch a change, trigger what you need to do.

    You can use vuex helpers to create a computed property bound to a store getter, then watch this property.

    https://vuex.vuejs.org/



  • Thanks.

    I can change the name of startEverything to be different on each page, store the page the user’s in and when needed, call the relevant startEverythingX.
    Or I can check the current route path and based on that, call the relevant startEverythingX.
    I was hoping there is a better/cleaner way for this. If not, I’ll go that way.



  • This post is deleted!


  • Some tricks that might help, in general:
    You can use this.$root.$once instead of $on to be sure that is only called one time. I guess in your case it might be called multiple times if the user action is triggered multiple times.
    If you want to have only one bind, you can also make a this.$root.$off on the beforeDestroy of your page.

    Also, you can use the navigation guards on your page and only bind on beforeRouteEnter and unbound on RouteLeave. This way you don’t have to know how it’s routed, only when.

    https://router.vuejs.org/guide/advanced/navigation-guards.html#in-component-guards



  • .$once won’t help because emit will still call startEverything of all pages the user had visited even after he left them.
    $off is the trick. Actually I discovered $off after posting my later-to-be-deleted post with another-related issue, not realizing it will solve also the first question I asked 🙂
    Thanks


Log in to reply