So I have some javascript class and in one method I use jQuery to bind function to click event. And within this function I need to call other methods of this class. In usual js function I did it through "this.method_name()", but here, I guess, jQuery redefines "this" pointer.
views:
32answers:
2
A:
jQuery doesn't redefine the this pointer, but that's how JavaScript functions work in general. Store a reference to the this pointer under a different name, and use that.
var self = this;
$("selector").click(function() {
self.method_name();
});
See this answer for more approaches.
Anurag
2010-07-29 16:50:36
The link pointed to a wrong answer. Updated
Anurag
2010-07-29 16:52:18
Oh wow, thx, works.
Tramp
2010-07-29 17:19:46
@Tramp - you're welcome. But note that this is still a hacky approach. Instead use `jQuery.proxy`, or even better the `bind` method that is now included in the standard. If it's not available in some browser, it's easy to define one - http://stackoverflow.com/questions/3018943/javascript-object-binding-problem-inside-of-function-prototype-definitions/3019431#3019431
Anurag
2010-07-29 17:29:59
A:
There are a few different ways to do this.
Anurag has a perfect example of one.
Two other ways are the jQuery Proxy class (Mentioned in other answers) and the 'apply' function
Now lets create an object with click events:
var MyObj = function(){
this.property1 = "StringProp";
// jQuery Proxy Function
$(".selector").click($.proxy(function(){
//Will alert "StringProp"
alert(this.property1);
// set the 'this' object in the function to the MyObj instance
},this));
//Apply Function
//args are optional
this.clickFunction = function(arg1){
alert(this.property1);
};
$(".selector").click(this.clickFunction.apply(this,"this is optional"));
};
CPettit
2010-07-30 00:12:01