繁体   English   中英

将Mediator Pattern与webpack和ES6模块一起使用导入导出

[英]Using Mediator Pattern with webpack and ES6 Modules import export

我编写了多个小部件,需要在它们之间进行通信。 我正在尝试使用中介者模式来做到这一点。 所以我有类似下面的内容。 我遇到的问题是调解员是2个不同的实例,而不只是1个。因此,widget_2实际上并未订阅正确的事件/消息。

我正在使用WebPack / Es6

我该如何克服?

 //mediator.js //ref: https://github.com/HenriqueLimas/mediator-pattern-es6/blob/master/src/mediator.js //app.js import Widget_1 from './widget_1.js'; import Widget_2 from './widget_2.js'; new widget_1 = new Widget_1(); new widget_2 = new Widget_2(); widget_1.run(); widget_2.run(); //widget_1.js import Mediator from './mediator.js'; const mediator = new Mediator(); export default class Widget_1 { constructor() { } run() { mediator.publish('widget1', 'hello there I am widget 1'); } } //widget_2.js import Mediator from './mediator.js'; const mediator = new Mediator(); export default class Widget_2 { constructor() { } run() { mediator.subscribe('widget1', function(message) { console.log('widget 1 says:' + message); }); } } 

如果您将调解员设为单身人士-根据定义,同一对象将在您使用它的任何地方共享。 此修改看起来像这样。

'use strict';

class Mediator {
    constructor() {
        this.channels = {};
    }

    subscribe(channel, fn) {
        if (!this.channels[channel]) this.channels[channel] = [];

        this.channels[channel].push({
            context: this,
            callback: fn
        });
    }

    publish(channel) {
        if (!this.channels[channel]) return false;

        var args = Array.prototype.slice.call(arguments, 1);

        this.channels[channel].forEach(function(subscription) {
            subscription.callback.apply(subscription.context, args);
        });

        return this;
    }

    installTo(obj) {
        obj.channels = {};

        obj.publish = this.publish;
        obj.subscribe = this.subscribe;
    }
}

var mediator = new Mediator();
export mediator;

但是,此时您实际上并不需要es6类,因为您将只使用一次它来创建一个新对象。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM