Event Bus & Event Emitter All In One
Event Bus & Event Emitter All In One
Event Bus
https://code.luasoftware.com/tutorials/vuejs/parent-call-child-component-method/
webpack & bug
// import EventEmitter from "./event-emitter";
import Vue from 'vue';
// import * as VueEventBus from 'vue';
// import * as VueEventBus from 'https://cdn.jsdelivr.net/npm/vue@2.6.11/dist/vue.esm.browser.js';
const log = console.log;
.$emit & .on
OK ???
import Vue from 'vue';
// import * as VueEventBus from 'vue';
// import * as VueEventBus from 'https://cdn.jsdelivr.net/npm/vue@2.6.11/dist/vue.esm.browser.js';
// A
// this.svgEventBus.fire(`update-status-data`);
this.svgEventBus.$emit(`update-status-data`);
// B
// this.svgEventBus.on(`update-status-data`, this.updateSVGData);
this.svgEventBus.$on(`update-status-data`, this.updateSVGData);
Event Emitter
// 5.实现一个 EventEmitter类,这个类包含以下方法:
// on(监听事件,该事件可以被触发多次)
// once(也是监听事件,但只能被触发一次)
// fire(触发指定的事件)
// off(移除指定事件的某个回调方法或者所有回调方法)
class EventEmitter {
constructor() {
this.events = {};
}
on(name, callback) {
this.events[name] = {
callback,
once: false,
};
}
once(name, callback) {
this.events[name] = {
callback,
once: true,
};
}
off(name) {
let keys = Object.keys(this.events);
if (keys.includes(name)) {
delete this.events[name];
}
}
fire(name, person) {
// dispatchEvent
let keys = Object.keys(this.events);
if (keys.includes(name)) {
let fun = this.events[name].callback;
let once = this.events[name].once;
// pass data
fun(person);
if (once) {
delete this.events[name];
}
}
}
}
const event = new EventEmitter();
const log = console.log;
event.on("drink", (person) => {
log(person + "喝水");
});
event.on("eat", (person) => {
log(person + "吃东西");
});
event.once("buy", (person) => {
log(person + "买东西");
});
event.fire("drink", "我");
// 我喝水
event.fire("drink", "我");
// 我喝水
event.fire("eat", "其它人");
// 其它人吃东西
event.fire("eat", "其它人");
// 其它人吃东西
event.fire("buy", "其它人");
//其它人买东西
event.fire("buy", "其它人");
//这里不会再次触发buy事件,因为once只能触发一次
event.off("eat") //移除eat事件
event.fire("eat", "其它人");
//这里不会触发eat事件,因为已经移除了
/*
3 解题思路:
class 存储 evnets, 按类型分别处理
*/
https://repl.it/@xgqfrms/EventEmitter-class
OK
fire & on
import EventEmitter from "./event-emitter";
// import Vue from 'vue';
// import * as VueEventBus from 'vue';
// import * as VueEventBus from 'https://cdn.jsdelivr.net/npm/vue@2.6.11/dist/vue.esm.browser.js';
const log = console.log;
data() {
return {
// Event Emitter
svgEventBus: new EventEmitter(),
// svgEventBus: new VueEventBus(),
// svgEventBus: new Vue(),
storeData: {
status: {
r: 0,
x: 0,
y: 0,
w: 0,
h: 0,
},
},
templateData: {},
seatData: {},
seatMap: "",
};
},
refs
©xgqfrms 2012-2020
www.cnblogs.com 发布文章使用:只允许注册用户才可以访问!
原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!
本文首发于博客园,作者:xgqfrms,原文链接:https://www.cnblogs.com/xgqfrms/p/12307870.html
未经授权禁止转载,违者必究!