Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Instance $dispatch won't return the value #2271

Closed
hiendv opened this issue Jan 31, 2016 · 3 comments
Closed

Instance $dispatch won't return the value #2271

hiendv opened this issue Jan 31, 2016 · 3 comments

Comments

@hiendv
Copy link

hiendv commented Jan 31, 2016

Hi, I'm a little confused about the vm.$dispatch since I expected it to return values from the listener's callback for further logic which could not be placed in the callback (imo) but it turned out to be the instance it self. I'm learning Vue and probably missed something.

var vm = new Vue({
    // omitted
    events: {
        'object:creating' : function (args) {
            // omitted
            return false;
        },
        'object:created' : function (args) {
            // omitted
        }
    }
});

var child = new Vue({
    parent: vm,
    // omitted
    methods: {
        performWhatever: function (args) {
            //
        },
        createObject: function (args) {
            // Pre-create
            if ( this.$dispatch('object:creating', args) === false ) {
                // Stop the creation
            }
            // The business logic
            this.performWhatever(args);

            // Post-create
            this.$dispatch('object:created', args);
        }
    }
})

As you can see, the pre-create operation is optional.
Thank you.

@fnlctrl
Copy link
Member

fnlctrl commented Jan 31, 2016

  1. $dispatch has no return value.
  2. Using the event system ($dispatch, $emit and so on) means your code will be asynchronous, which means what happens next is decided by the message receiver, so you don't write something like
    SomeAsyncCode === false
  3. In the javascript world, we use callbacks to handle asynchronous logic (Promises are better but it's not applicable here), and $dispatch expects you to pass multiple arguments including a callback function.
  4. Therefore, this is what you actually need:
this.$dispatch('object:creating', args, function() {
    // The business logic
    this.performWhatever(args);
})

and on the receiver's side,

events: {
    'object:creating' : function (args, callback) {
        // Do something with args and fire callback (or not)
        callback()
    }
}

@yyx990803
Copy link
Member

Thanks @fnlctrl for the explanation :)

@hiendv
Copy link
Author

hiendv commented Jan 31, 2016

@fnlctrl Thank you for explaination. It's asynchronous, I forgot, how embarrassing =D

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants