3

我创建了一个 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;

});
4

2 回答 2

6

尝试这样的事情:

!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;
});

这是一种通用语法,因为它也支持 CommonJS。请参阅此库中的示例 - https://github.com/ded/klass/blob/master/klass.js

于 2013-03-14T13:49:22.230 回答
0

当您不想用作 AMD 模块时,不确定为什么要将其写为 AMD 模块。

这根本不是一个好主意,但是您可以在将在全局上下文中MessageBus.js设置的 will之前添加自己的方法:MessageBus

function define(dep, func)(
  window.MessageBus = func()
)

更好的方法是有两个不同的版本。您可以拥有普通的 JS 版本并使用grunt-combine任务构建另一个带有 grunt 任务的版本

combine: {
  amd: {
    input: "amdContainer.js",
    output: "MessageBus-amd.js",
    tokens: [
      {
        token: "%MessageBus%",
        file: "MessageBus.js"
      }
    ]
  }

amdContainer.js

define([], function () {
  %MessageBus%
  return MessageBus;
});

消息总线.js

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;
    }
}
于 2013-03-14T13:25:46.890 回答