Binding Functions for Ajax Requests
Although function binding will be most often used for event handling (using
bindAsEventListener()), you will also need to bind functions when handling the response from Ajax requests. Since you don't need an event handler passed in (this concept doesn't apply to Ajax requests) we use
bind() instead of
bindAsEventListener(), once again accepting the variable to which the function should be bound.
In the previous article in this series I demonstrated a simple example of retrieving JSON data from the server and updating an element on the page with the returned data. I will now rewrite this same example using a class and function binding.
Listing 12 shows the PHP code used to return JSON data from the server. This is the script that will be accessed in the Ajax request. For a further explanation of how this all works, please refer to the previous article.
$person = array( 'name' => 'Quentin', 'country' => 'Australia' ); header('Content-type: application/json'); echo json_encode($person);
Now comes the interesting part. In Listing 13 we define a class called
MyClass which accepts a single argument to the constructor. This is the button that we observe the
click event on. We save the button as a class property so we can access it again the Ajax response handler. Again, we use
bindAsEventListener() so we can handle the event within the class.
Now when we handle the click event (the
_onButtonClick() method), we once again perform an Ajax request. The difference between doing it now and in the last article was that now we use
bind() so we can use the
MyClass instance in the
When the button is clicked, an Ajax request is performed. When the request is finished,
_onSuccess() handles the response and updates the button's container with the JSON data read from the Ajax request.