vue-epic-bus
Advanced tools
Comparing version 0.1.0 to 0.1.1
{ | ||
"name": "vue-epic-bus", | ||
"version": "0.1.0", | ||
"version": "0.1.1", | ||
"description": "Bus plugin for vue.js", | ||
@@ -5,0 +5,0 @@ "author": "Yauheni Prakopchyk", |
# vue-epic-bus | ||
Emit and subscribe on global scale | ||
Emit and subscribe to global bus from your components | ||
@@ -17,4 +17,49 @@ ## Installation | ||
import Vue from 'vue' | ||
import {BusPlugin} from './non-domain/AsvaSubs/BusPlugin' | ||
import {BusPlugin} from 'vue-epic-bus' | ||
Vue.use(BusPlugin) | ||
``` | ||
## Usage | ||
Subscribe: | ||
```html | ||
<script> | ||
export default { | ||
subs: { | ||
productUpdated (id) { | ||
console.log('Product updated', id) | ||
} | ||
}, | ||
} | ||
</script> | ||
``` | ||
Emit: | ||
```html | ||
<script> | ||
export default { | ||
methods: { | ||
productUpdated (id) { | ||
this.$cast('updated', id) | ||
} | ||
}, | ||
} | ||
</script> | ||
``` | ||
`$cast` could be used from template. | ||
```html | ||
<button @click="$cast('updated', id)">Update</button> | ||
``` | ||
If you're unhappy with default word choice for `$cast` and `subs` you can change it via plugin options: | ||
```js | ||
Vue.use(BusPlugin, { | ||
optionGroupName: 'subs', | ||
broadcastName: '$cast', | ||
}) | ||
``` |
@@ -1,3 +0,1 @@ | ||
import { Bus } from './Bus' | ||
const defaultOptions = { | ||
@@ -8,2 +6,35 @@ optionGroupName: 'subs', | ||
export class Bus { | ||
constructor () { | ||
// Subscribed components - array of closures | ||
this.subscribers = new Map | ||
} | ||
on (event, closure, component) { | ||
if (Array.isArray(event)) { | ||
event.forEach(event => this.on(event, closure, component)) | ||
return | ||
} | ||
const componentSubscribes = this.subscribers.get(component) || this.subscribeNew(component) | ||
componentSubscribes[event] = closure | ||
} | ||
emit (event, ...args) { | ||
this.subscribers.forEach((subscribes, component) => { | ||
subscribes[event] && subscribes[event].call(component, ...args) | ||
}) | ||
} | ||
wipeComponentSubscriptions (component) { | ||
this.subscribers.delete(component) | ||
} | ||
subscribeNew (component) { | ||
const componentSubscribes = {} | ||
this.subscribers.set(component, componentSubscribes) | ||
return componentSubscribes | ||
} | ||
} | ||
export const BusPlugin = { | ||
@@ -10,0 +41,0 @@ install (Vue, options = {}) { |
65
4222
6
57