Vue: how to catch all events?

Created on 10 Apr 2014  ·  14Comments  ·  Source: vuejs/vue

Hi,

if there a possibility to use VM $on() method to catch all incoming events?
It would be even cooler to enable wildcards like:

this.vm.$on('delete-*', function(){
//...
});

to catch all events starting with 'delete-'

Right now such functionality is useful for me for diagnostics, but I think it would be useful in several other scenarios as well.

Most helpful comment

For those looking to do the same thing with version 1.0+, the syntax is like this:

const old_on = this.$on;
this.$on = (...args) => {
  // custom logic here like pushing to a callback array or something
  old_on.apply(this, args);
};

All 14 comments

just a thought, maybe regex fits better in this case than wildcards :)

Here's a pretty hacky way to do it (if you take a look at src/emitter.js it should be fairly easy to understand)

var oldEmit = this.compiler.emitter.emit
this.compiler.emitter.emit = function () {
    console.log('got event: ' + arguments[0])
    oldEmit.apply(this, arguments)
}

Introducing wildcards/regex into the emitter implementation would bring about performance concerns, since the emitter is very central in the observation implementation and emit() is called a lot.

Thanks, this kind of hacky solution is good enough for me :smile:

For those looking to do the same thing with version 1.0+, the syntax is like this:

const old_on = this.$on;
this.$on = (...args) => {
  // custom logic here like pushing to a callback array or something
  old_on.apply(this, args);
};

example for version 2.* ?

Did you try that code? Should still work :)

@endoplasmic your solution can also work for 2.0

@njleonzhang ya, I edited my comment above to say 1.0+ so if others stumble on this, it's a bit more clear :)

@endoplasmic It's great and has no dependence to Vue implementation

@njleonzhang any example for this ? it did not work at my side.

@xiaolp endoplasmic has provided sample

i very stress

For those looking to do the same thing with version 1.0+, the syntax is like this:

const old_on = this.$on;
this.$on = (...args) => {
  // custom logic here like pushing to a callback array or something
  old_on.apply(this, args);
};

i add this code into beforeCreate but not work

Is there a way to catch all click events

Was this page helpful?
0 / 5 - 0 ratings