javascript - 将 Mediator 模式与 webpack 和 ES6 模块导入导出结合使用

标签 javascript design-patterns ecmascript-6 webpack mediator

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

关于javascript - 将 Mediator 模式与 webpack 和 ES6 模块导入导出结合使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38191049/

相关文章:

java - 在 Java 中使用 MVC 模式

c++ - 为 'solver' 类设计通用处理程序

c++ - 更好的基于请求的协议(protocol)实现结构

javascript - 如何使用变量和函数调用将 html 字符串解析到 JSX 客户端

javascript - 根据 javascript 中的模式验证 json

javascript - Chart.js - 如何将数组集合插入数据集

javascript - 使用jQuery show() 功能完整无动画

javascript - 如何调整数组大小

javascript - Uncaught ReferenceError : not defined

javascript - Object.Freeze Javascript