I am starting to get my feet wet using the publish/subscribe pattern in JavaScript, but now facing a problem I don't understand.
Take the following scenario:
On button click, a message is emitted, this works.
document.getElementById('myBtn').addEventListener('click', function() {
PubSub.publish('topic', data);
});
In an other part of my application, I pick up this message:
function MyObj() {
this.eventLog = [];
var token = PubSub.subscribe('topic', this.logger);
};
MyObj.prototype.logger = function(message, data) {
this.eventLog.push(data);
}
Here I want to store the published data in the eventLog
property of the MyObj
object. Unfortunately, this isn't working:
Uncaught TypeError: Cannot read property 'eventLog' of undefined
So it seems like the context of this
is lost – when I do console.log(this)
, the window
object is logged.
I know this
can be tricky for beginners, but until now I was always able to understand what is happening, but this leaves me completely puzzled. Of course MyObj
gets initialized before the message is published, so I don't see any problem here. Could somebody explain to me please what is happening here?