Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Controlling the value of 'this' in a jQuery event

Tags:

jquery

scope

this

I have created a 'control' using jQuery and used jQuery.extend to assist in making it as OO as possible.

During the initialisation of my control I wire up various click events like so

jQuery('#available input',              this.controlDiv).bind('click', this, this.availableCategoryClick); 

Notice that I am pasing 'this' as the data argument in the bind method. I do this so that I can get at data attached to the control instance rather from the element that fires the click event.

This works perfectly, however i suspect there is a better way

Having used Prototype in the past, I remember a bind syntax that allowed you to control what the value of 'this' was in the event.

What is the jQuery way?

like image 411
Pat Long - Munkii Yebee Avatar asked Feb 06 '09 11:02

Pat Long - Munkii Yebee


People also ask

What is $( this in jQuery?

$(this) is a jQuery wrapper around that element that enables usage of jQuery methods. jQuery calls the callback using apply() to bind this . Calling jQuery a second time (which is a mistake) on the result of $(this) returns an new jQuery object based on the same selector as the first one.

Is stop () a jQuery event method?

The event. stopPropagation() method is an inbuilt method in jQuery which is used to stop the windows propagation. In the DOM tree when setting an event with the child element and the parent element as well then if you hit on the child element event it will call both child and the parent element as well.

What is $scope in jQuery?

The scope is the binding part between the HTML (view) and the JavaScript (controller). The scope is an object with the available properties and methods. The scope is available for both the view and the controller. You have more detailed explanation here.

How can write onclick function in jQuery?

To trigger the onclick function in jQuery, click() method is used. For example, on clicking a paragraph on a document, a click event will be triggered by the $(“p”). click() method. The user can attach a function to a click method whenever an event of a click occurs to run the function.


1 Answers

You can use jQuery.proxy() with anonymous function, just a little awkward that 'context' is the second parameter.

 $("#button").click($.proxy(function () {      //use original 'this'  },this)); 
like image 117
Torbjörn Nomell Avatar answered Oct 12 '22 01:10

Torbjörn Nomell