1

I have the following javascript code.

var Test = function(){



    $("#"+elementId).click(function(){
        // How to call Test.callbackTest here?
    });

}

Test.prototype.callbackTest = function(){
    //code
}

If I want to call callbackTest() in clicking event, do I have to use this.callbackTest()?

or is there any better ways?

2 Answers 2

3

If you want to use from click function , this.callbackTest() wont work as this will be bound to window object and not your functions. There are various ways to do so .. one quick one

    var Test = function(){

       var that = this

        $("#"+elementId).click(function(){
            // How to call Test.callbackTest here?
             that.callbackTest();
        });

    }

    Test.prototype.callbackTest = function(){


  //code
}

jquery also provides a proxy solution , i recommend you check it out. if you use it your code will be like

  var Test = function(){

        $.proxy(this.callbackTest,this) // This ensures that wheneven callbackTest is called , 'this' inside callbackTest will be bound to current object , in this case Test 
        $("#"+elementId).click(function(){
            //AND THEN YOU CAN USE THIS here 
             this.callbackTest();
        });

    }

    Test.prototype.callbackTest = function(){


  //code
}
Sign up to request clarification or add additional context in comments.

2 Comments

@Moon, my pleasure : please also see modified reply.
// That proxy looks really interesting. Thanks a lot!!
1

You can make callbackTest private:

var Test = function(){
   function callbackTest(){
      //code
   }

   $("#"+elementId).click(callBackTest);
};

Otherwise it should be

var Test = function(){
   var me = this;
   $("#"+elementId).click(function(){
        me.callbackTest();
   });
};

8 Comments

how do you ensure that this is bound to Test ?
:) Then its same as proposed by me : but i would rather use 'that' instead of 'me' , its more standard across js guys
@Kooilnc // Thank you for your input. I have a question. Is it safe to use Test.callbackTest() instead? Just confirmed it works.
Yep, it is. But I offer a private function with it.
@Moon: you can call Test.callbackTest, but I would advise against it. I think the private function is a clearer solution 'scopewise'.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.