Looking for a way to use an event handler function within a Javascript object? Want to ensure that "this" inside the event handler is bound to the object it belongs to? Typically, "this" in an event handler refers to the object the event occurred on by default.
You can achieve this by incorporating an init function for the object where the binding takes place. Check out this jsfiddle example for a demonstration:
var myObject = {
init:function(){
this.downHandler = this.downHandler.bind(this);
},
downHandler:function(){
alert(this.someInfo);
},
someInfo:"hi there"
}
myObject.init();
If you want to avoid redefining "this" elsewhere, as it can reduce code maintainability, consider finding a solution that keeps the binding process within the method itself.
Attempts at immediate function execution might lead to issues, with "this" pointing towards the "window" object at that moment (especially in a browser context). Here's an example of such a trial:
var myObject = {
//more code
downHandler:(function(){
alert(this.someInfo);
}).bind(this), //this won't work as "this" is assigned to window during immediate execution
//more code
}
Is there a way to maintain the binding within the event handling function without using a separate init-function? Share your thoughts!