我创建了一个 js 库(MessageBus.js)并使其与 requirejs 兼容。现在我想在没有requirejs的情况下使用相同的库,即通过创建对象(new MessageBus())。
我在这篇文章中附上了我的库。
define([], function () {
var MessageBus = function () {
this.channelCallBackMap = {};
this.alreadyRegistred = false;
}
MessageBus.prototype = {
publish: function (channel, message) {
//Put original message and channel in the envelope and send it
var envelope = {
channel: channel,
message: message
};
var domain = location.protocol + '//' + location.host;
//Send message to all sibling iframes in the parent document
$("iframe", parent.document.body).each(function (i, frame) {
frame.contentWindow.postMessage(JSON.stringify(envelope), domain);
});
},
subscribe: function (channels, callbacks) {
var self = this;
if ($.isArray(channels) && $.isArray(callbacks)) {
$.each(channels, function (i, channel) {
self.channelCallBackMap[channel] = callbacks[i];
});
}
else if ($.isArray(channels)) {
$.each(channels, function (i, channel) {
self.channelCallBackMap[channel] = callbacks;
});
} else if (!$.isArray(callbacks)) {
this.channelCallBackMap[channels] = callbacks;
}
if (!this.alreadyRegistred) {
$(window).on('message', function (event) {
//Get the envelope, and from it get the original message as well as the channel
var domain = location.protocol + '//' + location.host;
if (event.originalEvent.origin !== domain) {
return;
}
var envelope = $.parseJSON(event.originalEvent.data);
if ($.inArray(envelope.channel, self.channels()) > -1) {
//Now it calls call-back function
self.channelCallBackMap[envelope.channel](envelope.channel, envelope.message);
}
});
}
this.alreadyRegistred = true;
},
channels: function () {
var keys = $.map(this.channelCallBackMap, function (value, key) {
return key;
});
return keys;
}
}
return MessageBus;
});