事件订阅类
class Event {
constructor() {
this.events = {} // 存放订阅事件队列
}
// 订阅事件
on(eventName, callback) {
// 如果订阅的事件存在,同一个事件名可订阅多好函数
if (this.events[eventName]) {
this.events[eventName].push(callback)
} else {
this.events[eventName] = [callback]
}
}
// 触发事件
emitter(eventName, params) {
this.events[eventName] && this.events[eventName].forEach(fn => fn.apply(this, [params]))
}
// 移除订阅事件
remove(eventName, callback) {
this.events[eventName] && this.events[eventName].filter(fn => fn != callback)
}
}
export default Event
使用方法
import React from 'react'
import { Button } from 'antd'
import Event from '@/utils/EventEmitter'
class EventEmitter extends React.Component {
constructor(props) {
super(props)
this.event = new Event()
this.event.on("click", this.handleone)
this.event.on("click", this.handleTwo)
}
handleone = params => {
console.log("第一件", params);
}
handleTwo = params => {
console.log('第二件', params);
}
handleClick = () => {
this.event.emitter('click', { name: 'click' })
}
render() {
return (
<Button type="primary" onClick={this.handleClick}>触发</Button>
)
}
}
export default EventEmitter
输出效果
image.png
网友评论