Monday, January 6, 2014

What is jQuery $.proxy. A simple jQuery $.proxy example

Introduction
 
So what is this jQuery $.proxy() all about? You've probably seen it and you read about stuff dealing with context. I hope to provide you some insight into this very useful method with some simple examples. I'll admit, I'm not that great with words so I would much rather provide code examples so that everyone can understand.

Shall we begin?

Problem

To start off, let's set up an example. Let's say we have a button and we want to attach a click handler. This handler will then perform an asynchronous call and then set the value of the button to the value that is returned from the server.

Here's our button HTML

<input type="button" id="somebutton" value="Before Click" />


So now, here you try to get a handle to the current element by using $(this) and you try to set up the value after your asynchronous $.get() request. However, you'll find that this does not work.

$('#somebutton').click(function(){
  var currentValue = $(this).val() // this represents the button clicked 
  console.log(currentValue) // prints out Before Click
  
  $.get('/someurl', function(result){
     $(this).val(result); // whoops this won't work!  
    
  });
}); 

What happened? Well, the context changed as soon as you execute the $.get() causing 'this' to not reference the button but now has taken the context of the $.get().

So you're thinking, 'How do I use $(this) in my $.get() success function!?'

Solution
 
Boom. $.proxy(). That's how. If you take a look at the jQuery documentation, one of the ways to use $.proxy is to specify two parameters. The function you want to execute and then the context you want applied. Context in this case just means 'this'. What do you want 'this' to refer to in your method call. So keeping this thought, let's now refactor our code up at the top to include $.proxy.


$('#somebutton').click(function(){
  $(this) // this represents the button clicked 
  
  $.get('/someurl', $.proxy(function(result){
     $(this).val(result); // huzzah! This will work!  
    
  }, this));
}); 

You will see I highlighted the $.proxy with an obnoxious yellow. The first parameter is our function that we want to specify a context for. The second parameter is what object we want 'this' to be when the first parameter (our function) is executed. So we're saying, let's take the value for 'this' and pass it to the success function whenever it gets executed.

So now, when the success function is called in $.get, 'this' will be pointing to the button.