Learn how to implement Vue Observer Pattern in your web app.
Probably one of my favorite design patterns is the Observer Pattern.
This design pattern allows you to subscribe and emit events from components of your app.
Different web frameworks offer different implementation of the Observer app.
Lucky me, implementing Observer in VueJS is piece of cake.
Actually the Observer in VueJS could be another Vue instance that we pass or make accessible by all our components.
import Vue from 'vue' // create a new Bus which will handle all our events const EventBus = new Vue() // We need to assign the bus to the root component Vue.prototype.$bus = EventBus
That’s all needed for the setup part.
You can now use this.$bus in all your Vue Components to subscribe and emit and dispatch events.
... // some random component emits events methods: { logout: function() { this.$bus.$emit('Some_Event/name', user) } } ... // some random component subscribes to the event created: function() { this.$bus.$on('Some_Event/name', (data) => { this.logout_user(data) }) }
There are two possible ways of generating the events and it mostly depends on who we want to receive that event.
$emit – targeting whole app
The $emit method will trigger an event in the current instance.
This means that all subscribers will be notified of this event.
$dispatch – targeting parent components
The $dispatch method propagates the event up in the parent chain.
The first parent subscriber will stop the event from propagating further unless it returns true.
In my next post I’ll describe how to create a Countdown Timer Component in VueJS.
Adios!
Pingback: Vue PIN code input component - Catalin Munteanu