Hanna
Hanna

Reputation: 10781

Understanding "this" in JQuery UI Widgets

Normally if I want to create a click event in JQuery I use the following syntax:

$("#test").on("click", function() { console.log($(this)); });

Here I can easily refer to the clicked element using the this keyword.

However in JQuery UI Widgets, it seems the format they want is:

this._on( $("li", this.list), {
      dblclick: function() { 
        console.log$(this);
      }
});

The problem is, that JQuery UI uses this for the widget, and I'm unable to refer to the this that was clicked. Is there a special syntax I need?

The problem with using the normal JQuery method is that I can't my widget variables inside of it due to the this then referring to what was clicked.

Do I need to create a temporary placeholder variable to make this work (like var temp = this.myVar), or is there another workaround?

Upvotes: 0

Views: 102

Answers (1)

Nomad101
Nomad101

Reputation: 1698

the this keyword in the ui plugin is the element that the ui plugin is currently operating on. I would take a look on how to make a plugin here:

http://docs.jquery.com/Plugins/Authoring

That should give you the required information. However you can think of the ui-plugin code as a single iteration of the .each() method and the this keyword is the currently searched element in the list that you would get from say this $("p.findMe"). So in essence the this keyword is used so that another search of the DOM tree is not necessary.

The click function has some arguments that you can pass, such as the target element. take a look at this: http://api.jquery.com/click/

Now specifically you will want to focus on the event object mentioned in the function overloads. By using function(event){} instead of function() in your dblclick you can use it to get the target element and all other information dealing with the event like its click location and parent elements.

Upvotes: 2

Related Questions