2

私は、さまざまな外部モジュール(「アクティビティ」と呼んでいます)をリアルタイムで選択してロードするために使用するsocket.ioを備えたnode.jsアプリを持っています。

すべてのモジュールは独自のイベントをソケットにバインドするため、あるモジュールから別のモジュールに変更するときに、前のモジュールが追加したすべてのイベント リスナーをソケットから削除できるようにしたいと考えています。

私はemitter.removeAllListeners()を使用しますが、それは私が望んでいないサーバーで定義したイベントも削除します。

私のコードは次のようになります。

app.js

// Boilerplate and some other code

var currentActivity;
io.sockets.on('connection', function(client){

    client.on('event1', callback1);
    client.on('event2', callback2);

    client.on('changeActivity', function(activityPath){
        var Activity = require(activityPath);
        currentActivity = new Activity();

        // Here I'd like some loop over all clients and:
        // 1.- Remove all event listeners added by the previous activity
        // 2.- Call currentActivity.bind(aClient) for each client
    });
})

アクティビティの例は次のようになります

someActivity.js

module.exports = function(){

    // some logic and/or attributes

    var bind = function(client){

        client.on('act1' , function(params1){ // some logic
        });
        client.on('act2' , function(params2){ // some logic
        });
        // etc.
    }
}

したがって、たとえばこの例では、someActivity.js別のアクティビティに変更する場合、すべてのクライアントから「act1」と「act2」のリスナーを削除できるようにしたいと考えていますが、「event1」のリスナーは削除しません。 event2」と「changeActivity」。

これを達成する方法について何か考えはありますか?

4

1 に答える 1

1

bind関数によって追加されたすべてのリスナーを削除するunbindというメソッドを各モジュールに作成します。

var fun1 = function(params1){ // some logic };    
var fun2 = function(params2){ // some logic };

module.exports = function(){    
    // some logic and/or attributes    
    var bind = function(client){    
        client.on('act1' , fun1);
        client.on('act2' , fun2);
    }

    var unbind = function(client){
        client.removeEventListener('act1',fun1);
        client.removeEventListener('act2',fun2);
    };
};

リスナーでクライアントにアクセスする必要がある場合は、クライアントをコンストラクターに渡すようにリファクタリングします。

function MyModule(client){
   this.client = client;
};
MyModule.prototype.fun1 = function(params1){
   //do something with this.client
};
MyModule.prototype.fun2 = function(params2){
   //do something with this.client
};
MyModule.prototype.bind = function(){
   this.client.on('act1' , this.fun1);
   this.client.on('act2' , this.fun2);
};
MyModule.prototype.unbind = function(){
   this.client.removeEventListener('act1' , this.fun1);
   this.client.removeEventListener('act2' , this.fun2);
};
module.exports = MyModule;

次に、次のように使用できます。

client.on('changeActivity', function(activityPath){
    var Activity = require(activityPath);
    var currentActivity = activityCache[activityPath] || new Activity(client); //use the existing activity or create if needed
    previousActivity.unbind();
    currentActivity.bind();
});
于 2013-04-23T21:48:35.137 に答える