PhpRiot
Become Zend Certified

Prepare for the ZCE exam using our quizzes (web or iPad/iPhone). More info...


When you're ready get 7.5% off your exam voucher using voucher CJQNOV23 at the Zend Store

Eight Weeks of Prototype: Week 6, Writing JavaScript Classes with Prototype

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.

Listing 12 Sending JSON data from the server (listing-12.php)
<?php
    $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.

Listing 13 Using bind() when handling Ajax requests (listing-13.html)
<html>
    <head>
        <title>Using bind() when handling Ajax requests</title>
        <script type="text/javascript" src="/js/prototype.js"></script>
    </head>
    <body>
        <div>
            <input type="button" value="Click Me!" id="myButton" />
        </div>
 
        <script type="text/javascript">
            var MyClass = Class.create({
 
                button : null,
 
                initialize : function(button)
                {
                    this.button = $(button);
                    this.button.observe('click', this._onButtonClick.bindAsEventListener(this));
                },
 
                _onButtonClick : function(e)
                {
                    var options = {
                        method    : 'get',
                        onSuccess : this._onSuccess.bind(this)
                    };
 
                    new Ajax.Request('listing-12.php', options);
                },
 
                _onSuccess : function(transport)
                {
                    var json = transport.responseJSON;
                    var msg = json.name + ' is from ' + json.country;
 
                    this.button.up().update(msg);
                }
            });
 
            new MyClass('myButton');
        </script>
    </body>
</html>

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 _onSuccess() method.

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.

In This Article