2012-01-06 30 views
6

Tôi không thể hiểu tại sao tôi không thể làm cho máy chủ của tôi chạy chức năng phát ra.Sử dụng chức năng phát ra trong node.js

Dưới đây là mã của tôi:

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... 
} 

Người nghe là:

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

Tất cả các loại console là thế này:

here 
here-2 

Bất cứ ý tưởng tại sao nó sẽ không in 'wtf'?

Trả lời

15

Vâng, chúng tôi thiếu một số mã nhưng tôi chắc chắn this trong cuộc gọi lại listen sẽ không là đối tượng myServer của bạn.

Bạn nên bộ nhớ cache một tham chiếu đến nó bên ngoài gọi lại, và sử dụng tài liệu tham khảo mà ...

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"); 
    }); 
} 

... hoặc bind bên ngoài this giá trị cho callback ...

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

Cảm ơn nhiều!!! – Itzik984

Các vấn đề liên quan