2014-12-05 3 views
0

저는 nodejs 모듈을 작성 중이며 이벤트 이미 터를 "scrappy.get"에 바인드하려고합니다. "scrappy"....에 바인딩 할 수있는 것 같습니다. "scrappy.get (key) .on ('complete'...."는 작동하지 않습니다.)자식 객체에 이벤트를 내 보냅니다.

자식 객체의 수 '

내 NodeJS 모듈 :

 var util = require('util'), 
    EventEmitter = require('events').EventEmitter; 

function Scrappy(id) { 
} 

util.inherits(Scrappy, EventEmitter); 

Scrappy.prototype.get = function (key) { 
    var self = this; 
    self.emit('complete', "here"); 
    **return this;** 
} 

module.exports = Scrappy; 

내 NodeJS 응용 프로그램 코드 :

var Scrappy = require('./scrappy.js') 
var scrappy = new Scrappy("1234"); 

scrappy.get("name").on('complete', function(data){ 
    console.log("secondary"); 
}); 

결과 :

scrappy.get("name").on('complete', function(data){ 
        ^
TypeError: Cannot call method 'on' of undefined 

편집 : 해결. "return this;"추가 그것을 위해 해결되었습니다. 고맙습니다!

답변

1

다른 기능을 사용하기 때문에 this이 다른 것입니다. 대신 캡처 할 필요가있는 단편적인 인스턴스의 this 변수 대신 액세스 :

Scrappy.prototype.get = function (key) { 
    var self = this; 
    redisclient.get(key, function(err, reply) { 
    self.emit('complete', reply); 
    }); 
}; 
또한

대신 수동으로 __proto__와 함께 프로토 타입을 돌연변이 같은, 일반적으로 어떤 노드 코어 사용 (많은 모듈 개발자가 무엇을 사용) 내장 된 util.inherits()입니다. 다른 것들은 get()에서 인스턴스를 반환하지 않는다는 것입니다. 다음은 이러한 변경 사항의 예입니다.

var util = require('util'), 
    EventEmitter = require('events').EventEmitter; 

function Scrappy(id) { 
} 
util.inherits(Scrappy, EventEmitter); 

Scrappy.prototype.sendToEngine = function(message) { 

}; 
Scrappy.prototype.set = function(key, value) { 

}; 
Scrappy.prototype.get = function(key) { 
    var self = this; 

    redisclient.get(key, function(err, reply) { 
    self.emit('complete', reply); 
    }); 

    return this; 
}; 

module.exports = Scrappy; 
+0

흠, 작동하지 않는 것 같습니다. nodejs 응용 프로그램에서 여전히 얻고 있습니다 : scrappy.get ("name") on ('완료', 함수 (데이터) { ^ TypeError : 정의되지 않은 'on'속성을 읽을 수 없습니다. – klinquist

+0

주요 문제 당신이'get()'에서'.on() '을 호출 할 수 있도록 Scrappy 인스턴스를 반환하지 않는다는 것입니다. – mscdex

+0

mscdex, 도와 주셔서 감사합니다. 그러나 저에게 도움이되지 않습니다 .. – klinquist

관련 문제