Reputation: 655
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!
Upvotes: 0
Views: 84
Reputation: 98926
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.
});
Upvotes: 2
Reputation: 123739
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
Upvotes: 5