I would like to use an event handler function as part of a Javascript object. I want to bind "this" inside the event handler to the object it is a method of, since the "this" inside an event handler is usually automatically assigned to the object the event happened on.
This can be done by using an init function for the object in which the binding happens (jsfiddle for tryout):
var myObject = {
init:function(){
this.downHandler = this.downHandler.bind(this);
},
downHandler:function(){
alert(this.someInfo);
},
someInfo:"hi there"
}
myObject.init();
I want to avoid this: Redefining it somewhere else decreases code maintainability. So I'm I'm in search for an solution that keeps the process of binding at the method itself.
I tried immediate function execution already, but at the point of immediate execution, the "this" point towards the "window" object (assuming a browser-context). My trials look like this:
var myObject = {
//more code
downHandler:(function(){
alert(this.someInfo);
}).bind(this), //does not work since at the point of immediate execution, the this is assigned to window
//more code
}
Can you think of a way that keeps the binding at the event handling function and not in a separate init-function?