最近遇到一個基於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');