簡體   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