Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sending $(this) in a callback

Tags:

jquery

I have this jQuery click event

$('#sidebar .nav a span').click(function () {
  var sidebar_nav = $(this);
  $("#main").load("type_change.php?id="+id, successCallback);

And then i have the callback to do the binding

var successCallback = function(responseText, textStatus, XMLHttpRequest) {
  //doing all the binding in here
}

Is there a way to pass $(this) or sidebar_nav or to the successCallback function so I can do something with it

like image 561
Matt Elhotiby Avatar asked Jun 10 '11 15:06

Matt Elhotiby


2 Answers

You could use $.proxy:

$("#main").load("type_change.php?id="+id, $.proxy(successCallback, $(this)));

This will set this inside successCallback to whatever you pass as second parameter.

If you want this still to refer to $("#main"), then you could change the callback to accept one more parameter:

var successCallback = function(responseText, textStatus, XMLHttpRequest, target) {
  //doing all the binding in here
}

and call it like so:

var sidebar_nav = $(this);
$("#main").load("type_change.php?id="+id, function() {
    var args = $.makeArray(arguments);
    args.push(sidebar_nav);
    successCallback.apply(this, args);
});

target will refer to sidebar_nav.

like image 160
Felix Kling Avatar answered Sep 28 '22 03:09

Felix Kling


Wrap it in a function, and use .apply() to invoke your function:

$('#sidebar .nav a span').click(function () {
  var sidebar_nav = this;
  $("#main").load("type_change.php?id="+id, function() {
       successCallback.apply( sidebar_nav, arguments );
   });

Now, this in your callback will be the element that was clicked, and the other arguments to the load() callback will be passed along as well.

like image 35
user113716 Avatar answered Sep 28 '22 02:09

user113716