0

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?

Community
  • 1
  • 1
Lars Hanke
  • 614
  • 5
  • 16
  • `.hover(this.hoverIn.bind(this), this.hoverOut.bind(this))` – elclanrs May 05 '15 at 09:14
  • I actually missed that answer, but it does not solve the full issue. It leads to the suggestion made by elclanrs. This brings tiles as this, but drops the event, i.e. jQuery $(this) does not work anymore. – Lars Hanke May 05 '15 at 14:43

1 Answers1

2

You can use a closure variable in the init method

'init': function () {
    var self = this;
    $("#tiles div.tile").hover(function () {
        self.hoverIn(this);
    }, function () {
        self.hoverOut(this);
    });
}

Your construct is not working because this inside the hover callbacks does not refer to the tiles object

Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
  • This doesn't solve the problem. this.hoverIn works fine in init! Making the callbacks accept an argument set to self, makes $(this) fail inside the callbacks. – Lars Hanke May 05 '15 at 20:29
  • Okay, made it. The trick is about function(){self.hoverIn(self,$(this))} to pass both parameters to the handler. I tried something similar before I asked the question, but must have done something wrong. Thanks for the hint - the bind() variant does not work for me. – Lars Hanke May 08 '15 at 16:28