Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling class methods within jQuery function

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.

like image 214
Tyth Avatar asked Jul 29 '10 16:07

Tyth


People also ask

How do you call a class in jQuery?

In jQuery, the class and ID selectors are the same as in CSS. If you want to select elements with a certain class, use a dot ( . ) and the class name. If you want to select elements with a certain ID, use the hash symbol ( # ) and the ID name.

How do I call a parameter from a function in jQuery?

In your functions add a parameter called e.g. element and replace $(this) with element . Calling the function you have to add the parameter $(this) . $(date_field). click(function() { clearFmt($(this), date_fmt); });

Can I call function in jQuery?

Calling a JavaScript library function is quite easy. You need to use the script tag. As almost everything we do when using jQuery reads or manipulates the document object model (DOM), we need to make sure that we start adding events etc. as soon as the DOM is ready.

What does $() stand for in jQuery?

In jQuery, the $ sign is just an alias to jQuery() , then an alias for a function. This page reports: Basic syntax is: $(selector).action() A dollar sign to define jQuery. A (selector) to "query (or find)" HTML elements.


2 Answers

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.

like image 99
Anurag Avatar answered Oct 04 '22 02:10

Anurag


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"));


};
like image 26
CPettit Avatar answered Oct 04 '22 02:10

CPettit