lundi 4 juillet 2016

Using Mediator Pattern with webpack and ES6 Modules import export

I have multiple widgets written and need to communicated between them. I am trying to use the mediator pattern to do that. So I have something like below. Problem I am having is mediator is 2 different instances instead of just 1. So widget_2 is not actually subscribing to correct event/message.

I am using WebPack/Es6

How can I overcome that?

//mediator.js
    //ref: http://ift.tt/29rGmez
    
    //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);
            });
        }
    }

Aucun commentaire:

Enregistrer un commentaire