-
Notifications
You must be signed in to change notification settings - Fork 0
/
eventBus.min.js
1 lines (1 loc) · 2.26 KB
/
eventBus.min.js
1
!function(e,t){var s="CreatePostMessageEventBus";"object"==typeof exports&&"object"==typeof module?module.exports[s]=t():"function"==typeof define&&(define.amd||define.cmd)?define(t):"object"==typeof exports?exports[s]=t():e&&(e[s]=t())}(this,function(){"use strict";var t;function s(e){this.options=e,this.sources=[],this.postMessageCenter=new n,this.postMessageCenter.watch(this.handler.bind(this))}function n(){this.watch=function(t){window.addEventListener("message",function(e){t(e)})},this.send=function(e,t,s){e.postMessage(t,s||"*")},this.EventData=e}function e(e,t){if(!this.valid(e))throw new Error("type is not correct");this.type=e,this.data=t}function i(e,t,s){this.eventNames=e,this.origin=t,this.source=s}return s.prototype.handler=function(s){var n=this;if(window===window.top)switch(s.data.type){case"REGISTER":var e=this.sources.find(function(e){return e.source===s.source});e?e.eventNames=s.data.data.eventNames:this.sources.push(new i(s.data.data.eventNames,s.origin,s.source)),this.postMessageCenter.send(s.source,new this.postMessageCenter.EventData("REGISTER-SUCCESS")),this.sources.forEach(function(t){t.eventNames.on.forEach(function(e){s.data.data.eventNames.emit.indexOf(e)&&n.postMessageCenter.send(t.source,new n.postMessageCenter.EventData("EMIT",e))})});break;case"PUSH":var t=s.data.data.name;this.sources.forEach(function(e){-1<e.eventNames.on.indexOf(t)&&(e.source===window?o(s):n.postMessageCenter.send(e.source,s.data))})}else o(s);function o(e){switch(e.data.type){case"REGISTER-SUCCESS":n.options.success&&"function"==typeof n.options.success&&n.options.success.call(n);break;case"PUSH":n.options.receive&&"function"==typeof n.options.receive&&n.options.receive.call(n,e.data.data);break;case"EMIT":n.options.request&&"function"==typeof n.options.request&&n.options.request.call(n,e.data.data)}}},s.prototype.init=function(){this.postMessageCenter.send(window.top,new this.postMessageCenter.EventData("REGISTER",{eventNames:{on:this.options.on||[],emit:this.options.emit||[]}}))},s.prototype.send=function(e){this.postMessageCenter.send(window.top,new this.postMessageCenter.EventData("PUSH",e))},e.prototype.EVENTS=["REGISTER","REGISTER-SUCCESS","PUSH","EMIT"],e.prototype.valid=function(e){return-1<this.EVENTS.indexOf(e)},function(e){return t||((t=new s(e)).init(),t)}});