// 最简单创建事件的方法,使用Event构造器
let myEvent = new Event('show');
// 创建带参数的自定义事件
let parmEvent = new CustomEvent('showParm',{
detail:{
parm:'王清最帅'
}
})
window.addEventListener('showParm',(event)=>{
console.log('得到的数据:',event.detail.parm)
},false)
window.addEventListener('show',()=>{
console.log('王清最帅')
},false)
// 触发事件
window.dispatchEvent(parmEvent)
window.dispatchEvent(myEvent);
//nodejs事件
let events = require('events');
let myEmitter = new events.EventEmitter();
myEmitter.on('someEvent',(message)=>{
console.log(message);
})
myEmitter.emit('someEvent','this is node event');
// 自定义发布订阅模式
let eventEmitter = {
list: {},
// 订阅
on: function (event,fn){
let _this = this;
(_this.list[event] || (_this.list[event] = [])).push(fn);
return _this;
},
// 发布
emit: function (...args){
let _this = this;
let fns = [..._this.list[[].shift.call(args)]];
if (!fns || fns.length == 0) {
return false;
}
fns.forEach(fn => {
fn.apply(_this, args)
});
return _this;
},
// 取消
off: function(event,fn){
let _this = this;
let fns = _this.list[event];
if (!fns) return false;
if (!fn) {
fns && (fns.length == 0)
} else {
fns.forEach( (item,index) => {
(item == fn || item.fn == fn ) && fns.splice(index,1);
} )
}
return _this;
},
// 监听一次
once: function(event,fn){
let _this = this;
function on(){
_this.off(event, on);
fn.apply(_this,arguments);
}
on.fn = fn;
_this.on(event,on);
return _this;
}
};
let f1 = (data)=>{
console.log('article',data);
}
let f2 = (data)=>{
console.log('article2',data);
}
eventEmitter.on('article',f1)
eventEmitter.on('article',f2)
eventEmitter.off('article',f1)
eventEmitter.once('wq',f2)
eventEmitter.emit('wq','测试')