1
class Foo extends EventEmitter {
    constructor(name) {
        this.name = name;
    }
    funcA(sourceRepositoryPath, branch) {

        this.emit('log', 'Hello from Foo');

        var bar = new Bar();
        bar.on('log', function(log) {
            this.emits('log', 'Hello from Foo from Bar');
        });
    }
}

How can i use the emit function from Foo inside the bar.on... function like the

this.emit('log', 'Hello from Foo');

function in ES6?

var foo = new Foo();
foo.funcA();

foo.on('log', function(log) {
    // expects : Hello from Foo && Hello from Foo from Bar 
    // gets : Hello From Foo   
});
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
orbatschow
  • 1,497
  • 2
  • 13
  • 26
  • Why do people always write "EC6"? Is that term used anywhere? – Bergi Aug 22 '15 at 20:50
  • I just shortend Ecmacript 6, but I don't know whether it's commonly used. – orbatschow Aug 22 '15 at 21:14
  • The standard abbreviation is ES6 (from [ECMA](https://en.wikipedia.org/wiki/Ecma_International)-[Script](https://en.wikipedia.org/wiki/ECMAScript)). I just wondered because I've seen "EC6" multiple times now while it really makes no sense :-) – Bergi Aug 22 '15 at 21:17
  • okay, thank you for mentioning that, i'll use the correct abbreviation in the future :) – orbatschow Aug 22 '15 at 21:43

2 Answers2

1

You have a different context inside the bar.on() handler so you need to either bind it to the outer scope:

bar.on('log', function(log) {
    this.emits('log', 'Hello from Foo from Bar');
}.bind(this));

or keep a reference to it:

var self = this;
bar.on('log', function(log) {
    self.emits('log', 'Hello from Foo from Bar');
});

or as you are using ES6/ES2015 you can use the arrow function which will keep the outer binding (and your transpiler will do one of the above for you):

bar.on('log', (log) => {
    self.emits('log', 'Hello from Foo from Bar');
});

Hope it helps!

Martin at Mavrix
  • 244
  • 2
  • 3
  • 6
1

The arrow function syntax solves this exact problem:

class Foo extends EventEmitter {
    constructor(name) {
        this.name = name;
    }

    funcA(sourceRepositoryPath, branch) {
        this.emit('log', 'Hello from Foo');

        var bar = new Bar();
        bar.on('log', (log) => {
            this.emits('log', 'Hello from Foo from Bar');
        });
    }
}

Other than a shorter, more concise syntax, arrow functions define a "lexical this", meaning the this keyword inside an arrow function resolves to the instance where the function is defined.

Amit
  • 45,440
  • 9
  • 78
  • 110