0

I have something like this:

var Tset = function(){
     this.a = $('div').text("lorem ipsum ..").appendTo('#a1');
     $(this.a).mouseover(function(){
              this.setBackground('red');
     });  
     this.setBackground = function(_color){
        $(this.a).css({'background-color':'color'});
        }
}

var x = new Tset();

My Problem is that i cant call this.setBackground from the mouseover callback function. How can I solve this problem? Thanks!

PSL
  • 123,204
  • 21
  • 253
  • 243
Oskar Alfons
  • 655
  • 1
  • 6
  • 8
  • related? http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example – John Dvorak Oct 01 '13 at 14:49
  • 2
    Dont you want `css({'background-color': _color})`? – Matt Greer Oct 01 '13 at 14:50
  • @OskarAlfons Just saw that you unaccepted my answer, i was just wondering what is wrong with the answer, a feed back would be really helpful for me to improve my answer. Thanks... – PSL Oct 02 '13 at 14:39

2 Answers2

5

Yes, inside the callback this refers to the element not the context of your instance. so try caching this.

var Tset = function () {
    var self = this; //<-- cache this to be used later
    this.a = $('div').text("lorem ipsum ..").appendTo('#a1');
    $(this.a).mouseover(function () {
        self.setBackground('red'); //invoke it with self
    });
    this.setBackground = function (_color) {
        $(this.a).css({
            'background-color': _color
        });
    }
}

var x = new Tset();

There are other techniques available similar to this, that are using Ecmascript5 function.bind, $.proxy etc.

Using bound function:

 var Tset = function () {

     this.a = $('div').text("lorem ipsum ..").appendTo('#a1');
     $(this.a).mouseover((function () {
         this.setBackground('red'); //Now this will be your instanc's context
     }).bind(this)); //bind the context explicitly  
     this.setBackground = function (_color) {
         $(this.a).css({
             'background-color': _color
         });
     }
 }

Except for the bound functions, caller determines the context inside the callback

Fiddle

PSL
  • 123,204
  • 21
  • 253
  • 243
2

Within jQuery event handlers, this is set to the element on which the event occurred.

However, in the parent function where you bind the callback, you can declare another variable to store that function's this, and refer to that variable in the callback.

Like so:

var Tset = function(){
    var that = this;// Declare another variable to store the parent function's "this" value.

     this.a = $('div').text("lorem ipsum ..").appendTo('#a1');
     $(this.a).mouseover(function(){
              that.setBackground('red');// And refer to that variable in your callback.
     }); 
Paul D. Waite
  • 96,640
  • 56
  • 199
  • 270