本篇内容主要讲解“如何用js实现自定义事件”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“如何用js实现自定义事件”吧!
1、指定谁是发布者。
2、给发布者添加一个缓存列表来存储回调,以便通知订阅者。
3、发布消息时,发布者会遍历这个列表,依次触发存储在其中的订阅者回调函数。
实例
const salesOffices = {} // 定义售楼处
salesOffices.clientList = [] // 缓存列表,存放订阅者的回调函数
salesOffices.listen = function(fn) { // 增加订阅者
this.clientList.push(fn) // 添加进缓存列表
}
salesOffices.trigger = function() { // 发布消息
for(let i = 0, fn; fn = this.clientList[i++];) {
fn.apply(this, arguments) // arguments 是发布消息时带上的参数
}
}
// 测试
salesOffices.listen((price, squareMeter) => { // 小明订阅消息
console.log('价格=' + price)
console.log('squareMeter=' + squareMeter)
})
salesOffices.listen((price, squareMeter) => { // 小红订阅消息
console.log('价格=' + price)
console.log('squareMeter=' + squareMeter)
})
salesOffices.trigger(2000000, 88)
salesOffices.trigger(3000000, 110)
到此,相信大家对“如何用js实现自定义事件”有了更深的了解,不妨来实际操作一番吧!这里是天达云网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!