最近遇到一个基于jQuery项目,项目中的功能节点页面都是经过iframe实现,可是各个iframe之间有时须要相互通讯,互相相应一些事件,为了更愉快的编码因此想到了自定义事件,还别说用起来居然有点像vue的组件通讯vue
top.events = { on: function (name, func) { if(!this.handles){ this.handles = {}; } 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');