2

Is it possible to have namespaces with events, like in JQuery?

like be able to do:

$.on('click.namespace')
$.on('change.namespace')
$.off('.namespace') // unregister both
3
  • The event names are just strings, so you could theoretically do it as you are setting it in the example. Unsettings however would require more work, you could probably store the events in an array or object and then loop them for the $.off call Commented Nov 1, 2018 at 18:23
  • I don't why this is necessary? This looks like an Event Bus or Vuex thing. Commented Nov 2, 2018 at 5:59
  • You need to find a third-party library that offers the feature, such as my own github.com/louisameline/vue-nsel (MIT) Commented Jul 19, 2019 at 13:36

1 Answer 1

2

No, and usually not needed in Vue:

When using @eventName="handler" in the template, Vue handles the registration and de-registration of the event handlers.

And because you can specify the name of the events a components $emits you won't have naming collisions.

To manually register & deregister an eventlistener when the component is destroyed:

emitter.$on(component.handleClick)
component.$on("$destroy", () => emitter.$off('click', component.handleClick))

Declare the handleClick in the methods: that creates a unique callback bound to the component.

Sign up to request clarification or add additional context in comments.

2 Comments

of course it's needed. I have different modules that are hooked on the same events. And I have no way to unregister handlers for a module when it is destroyed, because $off unregisters them all. And I'm not using events inside a template btw
If you pass an unique callback to on you can deregister that specific callback if you pass that as the second parameter to call $off.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.