我創建了一個js庫(MessageBus.js),並使其與requirejs兼容。現在我想使用沒有requirejs的相同的庫,即通過創建對象(新的MessageBus())。我怎樣才能做一個js函數,可以使用和不使用requirejs
我附上我的lib與這篇文章。
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;
});
史密斯嗨。你能告訴我什麼是!功能的重要性離子? – 2013-03-19 09:15:05
這是一個較短的自調用函數語法 - http://stackoverflow.com/questions/5827290/javascript-function-leading-bang-syntax – 2013-03-19 10:20:25