2017-08-10 16 views
0

クラスの各インスタンスをイベントエミッターに関連付けることを試みています。私がしようとしている以下:イベントエミッターを各ES6クラスのインスタンスとノード内に接続します

const events = require("events"); 
const eventEmitter = new events.EventEmitter(); 

class Camera { 
    constructor(ip) { 
     this.ip = ip; 

     eventEmitter.on("recordVideo", function() { 
      this.recordClip(); 
     }); 
    } 

    recordClip() { 
     console.log("record " + this.ip); 
    } 
} 

var cam = new Camera("0.0.0.0"); 
eventEmitter.emit("recordVideo"); 

しかし、私は戻って取得:

TypeError: this.recordClip is not a function 

がどのように私は私のクラスの各インスタンスがイベントをリッスン持つことができますか?

+0

[あなたが既に得た答え](https://stackoverflow.com/a/45601755/1048572)のコードを使用するだけではどうですか? – Bergi

+0

@bergi申し訳ありません、私はコピーして、私の関数呼び出しをコンストラクタに貼り付けました。私は作られた縛りの変化に気付かなかった。 –

答えて

1

あなたの問題はthisは、イベント・エミッターではなく、クラスのコンテキストであるということです。したがって、は方法としてrecordClipを持っていません。

はあなたがバインドする必要があり、(個人的に、私はこれが最善であると思うし、これを行うための最も近代的な/読み込み可能な方法)

eventEmitter.on("recordVideo",() => { 
    this.recordClip(); 
}); 

をまたは:あなたは、どちらかの字句矢印機能を使用して、コールバックをバインドする必要があります適切な範囲:

eventEmitter.on("recordVideo", function() { 
    this.recordClip(); 
}).bind(this); 

それとも、self方法論を経てthisへの参照を行うことができます。

class Camera { 
    constructor(ip) { 
     this.ip = ip; 
     const self = this; //assign this to self 
     eventEmitter.on("recordVideo", function() { 
      self.recordClip(); //use self, not this here 
     }); 
    } 

    recordClip() { 
     console.log("record " + this.ip); 
    } 
} 
+0

これらの方法のどちらがより標準的と見なされるか、またはより読みやすいとわかりますか? –

+1

@PhilipKirkbride私は実際に私の編集でそれを追加しました:)私は矢関数を使用することがここで最も標準的な/読める方法論だと思います。 –

1

コールバック関数のコンテキストが期待するものを参照していないためです。矢印機能を追加します。ここで

const events = require("events"); 
const eventEmitter = new events.EventEmitter(); 

class Camera { 
    constructor(ip) { 
    this.ip = ip; 

     eventEmitter.on("recordVideo",() => { 
     this.recordClip(); 
     }); 
    } 

    recordClip() { 
     console.log("record " + this.ip); 
    } 
} 

    var cam = new Camera("0.0.0.0"); 
    eventEmitter.emit("recordVideo"); 

は、いくつかのドキュメントです:ここhttps://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

関連する問題