You are reading a single comment by @AndreyVS and its replies. Click here to read the full conversation.
  • Hi Everyone! On Puck I try to organize communication between objects with events (see Object.emit and discussion here). However, I cannot emit an event within a prototype function with 'this'. Thus if e.g. I have two step up modules, I cannot subscribe directly to each of them, and need to add either a module id as an event argument or additional empty object (see below).

    In comments here is what I'd want:

    function aClass() {};
    
    aClass.prototype.testEmit = function() {
      setTimeout(()=>aClass.emit('TestEvent'),­ 1000); //this.emit(...) here will not emit!
    }
    
    var a = new aClass();
    aClass.on('TestEvent', ()=>console.log('Got event')); //would like 'a.on(...)'
    a.testEmit();  // get 'Got event' printed in log
    
    var a1 = new aClass();
    a1.testEmit(); // get another 'Got event' printed in log
    

    Here is a way round with an empty object:

    function aClass() {
      this.emitter = {};
    };
    
    aClass.prototype.testEmit = function() {
      setTimeout(()=>this.emitter.emit('TestEv­ent'), 1000); //now it works
    }
    
    var a = new aClass();
    a.emitter.on('TestEvent', ()=>console.log('Got event')); //now we subscribe only to a
    a.testEmit(); //get 'Got event' in console
    
    var a1 = new aClass();
    a1.testEmit(); //get nothing
    

    Why can't I use this.emit(...)?

About

Avatar for AndreyVS @AndreyVS started