Использование функции emit в node.js - PullRequest
6 голосов
/ 06 января 2012

Я не могу понять, почему я не могу заставить свой сервер запускать функцию emit.

Вот мой код:

myServer.prototype = new events.EventEmitter;

function myServer(map, port, server) {

    ...

    this.start = function () {
        console.log("here");

        this.server.listen(port, function () {
            console.log(counterLock);
            console.log("here-2");

            this.emit('start');
            this.isStarted = true;
        });
    }
    listener HERE...
}

Слушатель:

this.on('start',function(){
    console.log("wtf");
});

Все типы консолей таковы:

here
here-2

Есть идеи, почему он не напечатает 'wtf'?

Ответы [ 2 ]

15 голосов
/ 06 января 2012

Ну, нам не хватает некоторого кода, но я почти уверен, что this в обратном вызове listen не будет вашим myServer объектом.

Вы должны кешировать ссылку на неговне обратного вызова и используйте эту ссылку ...

function myServer(map, port, server) {
    this.start = function () {
        console.log("here");

        var my_serv = this; // reference your myServer object

        this.server.listen(port, function () {
            console.log(counterLock);
            console.log("here-2");

            my_serv.emit('start');  // and use it here
            my_serv.isStarted = true;
        });
    }

    this.on('start',function(){
        console.log("wtf");
    });
}

... или bind внешнее значение this для обратного вызова ...

function myServer(map, port, server) {
    this.start = function () {
        console.log("here");

        this.server.listen(port, function () {
            console.log(counterLock);
            console.log("here-2");

            this.emit('start');
            this.isStarted = true;
        }.bind( this ));  // bind your myServer object to "this" in the callback
    };  

    this.on('start',function(){
        console.log("wtf");
    });
}
0 голосов
/ 07 августа 2018

Для новых людей обязательно используйте функцию стрелки ES6 всякий раз, когда вы можете привязать контекст «this» к вашей функции.

// Automatically bind the context
function() {
}

() => {
}

// You can remove () when there is only one arg
function(arg) {
}

arg => {
}

// inline Arrow function doesn't need { }
// and will automatically return
function(nb) {
  return nb * 2;
}

(nb) => nb * 2;
...