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 8, A Complete Prototype Example

Retrieving and Displaying the List of Contacts

Finally we must implement the AddressBook_Contacts, which is used to load the existing contacts using Ajax and populate them on the index.html page (in the #contacts div).

Listing 11 shows the code for this class, which we store in the Contacts.js file in the /js/AddressBook directory. We begin the class by defining a basic HTML template that is used to format each contact. We use the Prototype Template class to do so (as covered in the previous article in this series). Next we observe the custom event (contacts:added) then load the existing contact.

Listing 11 Loading the existing contacts and displaying new contacts (Contacts.js)
var AddressBook_Contacts = Class.create({
 
    // define the template used to display each contact
    template : new Template(
        '<div class="contact">'
      + '    <span class="name">#{name}</span>'
      + '    <span class="email">(#{email})</span>'
      + '    <div class="location">'
      + '        #{location}'
      + '    </div>'
      + '</div>'
    ),
 
    initialize : function(container)
    {
        this.container = $(container);
 
        // observe the custom event so we know when a new contact is created
        Event.observe(document, 'contacts:added', this._onContactAdded.bindAsEventListener(this));
 
        // load existing contacts
        this.load();
    },
 
    load : function()
    {
        var options = {
            method    : 'get',
            onSuccess : this._onLoadSuccess.bind(this)
        };
 
        // submit request to retrieve contacts
        new Ajax.Request('contacts.php', options);
    },
 
    _onLoadSuccess : function(transport)
    {
        var json = transport.responseJSON;
 
        // clear the contacts container
        this.container.update();
 
        // now populate the container with each contact
        json.each(function(contact) {
            this.container.insert(this.template.evaluate(contact));
        }, this);
    },
 
    _onContactAdded : function(e)
    {
        this.container.insert(this.template.evaluate(e.memo.contact));
    }
});

Now that all the files have been created you should be able to load the index.html file in your browser and create contacts. When you create a new contact it should be submitted via Ajax then added to the list of contacts without reloading the page.

If you find that your code isn't work as intended, I highly recommend you make use of the Firebug plug-in for Firefox. It allows you to easily debug your JavaScript as well to see any HTTP sub-requests that are performed (that is, Ajax requests), including request and response headers and the response body. 

In This Article