I want to encapsulate my Javascript code for certain objects in structures as indicated below. However, I ran into trouble with the semantics of this
.
While this
during tiles.init()
refers to the tiles
object, in the event handlers it refers to the event, i.e. I cannot use this
to call other methods from my object.
Is there any way to pass the object to the event handlers, such that I do not have to use the global variable to call my own sub-routines and still retain this
from the callback context?
I put up a JSFiddle here. This is the working JS part:
myData = {
'color': "red",
'makeRed': function(){
// don't want reference to global here!
$(this).css("color",myData.color);
},
'reset': function(){
$(this).css("color","");
},
'init': function(){
$("#click").hover(this.makeRed,this.reset);
}
};
myData.init();
I found several solutions like this and this idea to pass additional arguments. The question has been marked a duplicate of this, but using .bind()
wastes the this
required for the jQuery inside the callback.
Any idea how to get both tiles
and this
of the event context to the handler function without using globals?