I have this basic code:
app.Modules.myModule = {
init: function(){
this.bindEvents();
},
bindEvents: function(){
app.Events.on('user:added', this.userAdded.call(this));
this.username = $('#username');
},
userAdded: function(event, params){
console.log(params);
this.username.text(params.username);
}
};
Now the problem I have, is that if I call this.userAdded as it is, then params doesn’t get passed on to the userAdded function. If I don’t use ‘call’ and just do this.userAdded, inside the userAdded function, then the context of ‘this’ is the jQuery event and not the ‘app.Modules.myModule’ like I need it to be.
So my question is, how can I keep the context of ‘this’ inside the userAdded function to the Object itself (myModule) and be able to pass it the params argument?
if you define your module as a function, the context can be set to a variable upon instantiation. For example:
The context variable will now reference the context of the object, and can be used within the functions. Make sure that you use the “new” keyword when initializing the object.