Nil*_*ete 3 javascript jquery requirejs
我创建了一个js库(MessageBus.js)并使其与requirejs兼容.现在我想使用不带requirejs的同一个lib,即创建对象(新的MessageBus()).
我正在用这篇文章附上我的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;
});
Run Code Online (Sandbox Code Playgroud)
尝试这样的事情:
!function (name, definition) {
if (typeof define == 'function' && define.amd) {
define(definition);
} else if (typeof module != 'undefined') {
module.exports = definition();
} else {
this[name] = definition();
}
}('MessageBus', function() {
var MessageBus = function () {
this.channelCallBackMap = {};
this.alreadyRegistred = false;
};
// Rest of the object
return MessageBus;
});
Run Code Online (Sandbox Code Playgroud)
这是一种常见的语法,因为它也支持CommonJS.请参阅此库中的示例 - https://github.com/ded/klass/blob/master/klass.js
| 归档时间: |
|
| 查看次数: |
409 次 |
| 最近记录: |