Question

First of all I would like say it is the first time i'm working with a reactor pattern. I've tried a bit of everything with the knowledge I have but without any succes. This is my script so far:

function Reactor(){
  this.events = {};
}

Reactor.prototype.registerEvent = function(eventName){
  this.events[eventName] = {name: eventName, callbacks: []};
};

Reactor.prototype.dispatchEvent = function(eventName, eventArgs){
  for(var i in this.events[eventName].callbacks) {
    this.events[eventName].callbacks[i](eventArgs);
  }
};

Reactor.prototype.addEventListener = function(eventName, callback){
    if(typeof(this.events[eventName]) == 'undefined') this.registerEvent(eventName);
    return this.events[eventName].callbacks.push(callback) - 1;
};

and to test the script I have this

var test = new Reactor();

test.addEventListener('ping', function() {
    console.log(this); //I want this to be the 'test' object
});

test.dispatchEvent('ping');

So I create a new reactor object, adds a eventlistener to it and then dispatch the event. But in the callback function I want "this" to be the "test" object.

Was it helpful?

Solution

You can call your methods with call or apply to force a particular this value:

Reactor.prototype.dispatchEvent = function(eventName, eventArgs){
  for(var i in this.events[eventName].callbacks) {
    this.events[eventName].callbacks[i].apply(this, eventArgs);
  }
};

(assuming eventArgs is an array, the callback will be called with each element from the array passed as a separate argument)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top