-
Notifications
You must be signed in to change notification settings - Fork 0
Open
Description
当一个对象的状态发生改变时,所有依赖与它的对象都将得到通知,在实际开发中,若多个事件共同依赖同一条件,那么可以将这些事件放入一个数组之中。在我看来,这样做更加清晰规范,便于项目的维护。下面手写一个简单的例子:
const eventsWacth = (function(){
var events = {} //定义一个存储事件的对象
function on(name, action) { //name: 事件名称; action: 对应执行函数
events[name]= events[name] || []
events[name].push({ //将执行函数push进数组列表
action
});
}
function emit(name, args) {// args: 参数
if (!events[name]) { //未找到 return
return
}
for(let i = 0; i < events[name].length; i ++) { //事件名称有可能对应多个函数
if(events[name][i] && events[name][i].action) { //如在事件数组中找到对应函数 执行
events[name][i].action(args)
}
}
}
function off(name){ //销毁
delete events[name];
}
return {
on,
emit,
off
}
})()
var f1 = function(val) {console.log(1111 + val)}
var f2 = function(val) {console.log(2222 + val)}
eventsWacth.on('first', f1)
eventsWacth.emit('first', 'tyty') //1111tyty
eventsWacth.on('first', f2)
eventsWacth.emit('first', 'tyty')// 打印1111tyty和2222tyty
eventsWacth.on('second', f1)
eventsWacth.emit('second', 'hello world!') // 1111hello world!
每天学习一点点
Metadata
Metadata
Assignees
Labels
No labels