JavaScript自定义事件

4次阅读

共计 612 个字符,预计需要花费 2 分钟才能阅读完成。

标题 JavaScript 自定义事件
最近遇到一个基于 jQuery 项目, 项目中的功能节点页面都是通过 iframe 实现, 但是各个 iframe 之间有时需要相互通信, 互相相应一些事件, 为了更愉快的编码所以想到了自定义事件, 还别说用起来竟然有点像 vue 的组件通信
top.events = {
on: function (name, func) {
if(!this.handles){
this.handles = {};
}
if(!this.handles[name]){
this.handles[name] = ”;
}
else this.handles[name] = func;
},
emit: function (name) {
if(this.handles[name]){
//arguments 是伪数组所以通过 call 来使用 slice
this.handles[name].apply(null, Array.prototype.slice.call(arguments, 1));
}
},
destory: function (name) {
if(this.handles && this.handles[name]) delete this.handles[name];
}
};
// 绑定
top.events.on(‘test’, function() {});

// 触发
top.events.emit(‘test’, param));

// 销毁
top.events.destory(‘test’);

正文完
 0