Why is jQuery parent().index() not working when used in jQuery widget

153 views Asked by At

I am creating a jQuery widget. I have this code example set up to match my original situation as closely as possible...

function someFunction(){
$("#somediv").on("click", ".rem", $.proxy(this.handleEvent, this));
}

function handleEvent(that){
    var testval = $(that).parent().index();
   console.log(testval);
}

someFunction();

JSBin here ----> http://jsbin.com/cewevo/

The issue is that, regardless of the 'X' button clicked on, the index result is '-1'. I have tried every element path I can think of, but the best I can do is get the innerText of the related button click. I need the index so that I can delete the correct element in the original array that was used to populate the list.

Code like this works as expected, except the lines below does not work for me in the widget context.

  $("somediv").on("click", ".rem", function(){
    var testval = $(this).parent().index();
});

I am using the .proxy function to try to get the right context to the function "handleEvent".

3

There are 3 answers

1
M. Page On BEST ANSWER

I don't think that using $.proxy is the best option here since, in your case handleEvent always receives the mouse event as argument.

The following code gives the result that you want.

function someFunction(){
    $("#somediv").on("click", ".rem", $.proxy(this.handleEvent));
}

function handleEvent(that){
    var testval = $(that.target).parent().index();
    console.log(testval);
}
0
Brian Glaz On

I've updated your code so it behaves how you are expecting:

function someFunction(){
$("#somediv").on("click", ".rem", function() { 
      $.proxy(handleEvent, this)();
    });
}

function handleEvent(){
   var testval = $(this).parent().index();
   console.log(testval);

}

someFunction();

They key here is to wrap $.proxy inside a function(). It wasn't working as expected because the context was wrong. Without the inner function, this inside of $.proxy was referring to jQuery itself, and not the jQuery object that was clicked on. The function parameter to on reccieves the clicked element as its context.

2
ajmajmajma On

I think you are over complicating it.

http://jsbin.com/kekadubeca/2/

just add a class on the UL so it's a bit easier to call and viola

var items = $('.myUl li').click(function() {
    console.log(items.index(this));

});