【问题标题】:Using Mediator Pattern with webpack and ES6 Modules import export将中介者模式与 webpack 和 ES6 模块一起使用导入导出
【发布时间】:2016-07-04 19:17:24
【问题描述】:

我编写了多个小部件,需要在它们之间进行通信。我正在尝试使用中介模式来做到这一点。所以我有类似下面的东西。我遇到的问题是调解器是 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);
            });
        }
    }

【问题讨论】:

  • 将调解器设为constructorrun 方法的参数,在您的app.js 中实例化它并将其传递给每个实例。
  • 或者使用单例模式修改你的中介

标签: javascript design-patterns ecmascript-6 webpack mediator


【解决方案1】:

如果您将调解器设为单例 - 根据定义,同一个对象将在您使用它的任何地方共享。这种修改可能看起来像这样。

'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 类,因为你只会使用它一次来创建一个新对象。

【讨论】:

    猜你喜欢
    • 2020-02-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-11
    • 2017-06-29
    • 1970-01-01
    • 2021-11-27
    • 1970-01-01
    相关资源
    最近更新 更多