Reputation: 3810
In the following snippet I made an event emitter which executes all the event when called. I used a function constructor and added on
and emit
methods on it.
The even transfer
updates the objects property amount
.
But when I access this.amount
inside on
it returns undefined.
emitter.js
function Account(n) {
this.balance=n;
this.events = {}
}
Account.prototype.on = function(type, listener){
this.events[type] = this.events[type] || [];
this.events[type].push(listener);
}
Account.prototype.emmit = function(type){
if(this.events[type]) {
this.events[type].forEach(listener => {
listener();
});
}
console.log("Amount transfered. Total Balance is " + this.balance);
}
module.exports = Account;
app.js
const Account = require('./emitter');
const myAccount = new Account(5);
myAccount.on('transfer', function(amount = 10){
this.balance += amount;
console.log(amount + ' Rs. has been transferrered! Balance is ' + this.balance);
});
myAccount.on('transfer', function(amount = 30){
this.balance += amount;
console.log(amount + 'Rs. has been transferrered! Balance is ' + this.balance);
});
myAccount.on('transfer', function(amount = 40){
this.balance += amount;
console.log(amount + 'Rs. has been transferrered! Balance is ' + this.balance);
});
myAccount.emmit('transfer');
This is what I have already tried.
I think that this.events is already an object so this
inside it will refer to the current object not the parent object.
So tried accessing the property myAccount.amount
. Still it returns undefined
I also tried storing reference of this
in a variable that
and instead of accessing property in this.amount
, i tried that.amount
still undefined.
Upvotes: 0
Views: 114
Reputation: 27460
Your are not passing 'this' to your listener callback function.
Change listener()
invocation to this:
listener.call(this);
Upvotes: 2