Nodejs EventEmitter - Define scope for listener function

前端 未结 3 830
野趣味
野趣味 2020-12-20 16:27

I\'d like to have something like this work:

var Events=require(\'events\'),
    test=new Events.EventEmitter,
    scope={
        prop:true
    };

test.on(\         


        
相关标签:
3条回答
  • 2020-12-20 17:04

    That won't work, and emit only has a convenient way to pass parameters, but none for setting this. It seems like you'll have to do the binding stuff yourself. However, you could just pass it as a parameter:

    test.on('event',function(self) {
       console.log(self.prop===true);//would log true
    });
    test.emit('event', scope);
    
    0 讨论(0)
  • 2020-12-20 17:21

    No, because the this value in the listener is the event emitter object.

    However what you can do is this

    var scope = {
      ...
    };
    scope._events = test._events;
    test.emit.call(scope, ...);
    

    The reason your event handler did not get called is because all the handlers are stored in ._events so if you copy ._events over it should work.

    0 讨论(0)
  • 2020-12-20 17:27

    I came across this post when Google searching for a package in NPM which handles this:

    var ScopedEventEmitter = require("scoped-event-emitter"),
        myScope = {},
        emitter = new ScopedEventEmitter(myScope);
    
    emitter.on("foo", function() {
        assert(this === myScope);
    });
    
    emitter.emit("foo");
    

    Full disclosure, this is a package I wrote. I needed it so I could could have an object with an EventEmitter property which emits for the containing object. NPM package page: https://www.npmjs.org/package/scoped-event-emitter

    0 讨论(0)
提交回复
热议问题