Building Collections Efficiently Using jQuery

Published Mar 13, 2012
jQuery JavaScript

One issue that is commonly faced in an AJAX based website is the building of a collection or list of items. The collection is dynamic meaning items can be added or removed and this is done so via AJAX calls. The goal is to keep the JavaScript and HTML components separate while keeping the code understandable and maintainable. There are a few frameworks out there to do this for you like the more popular backbone.js however I wanted to present a simpler solution without the use of any frameworks.

The Problem

We have some type of collection of common items that can be added or removed on the fly via AJAX calls and no page refreshes.

<div id="blurbs_table"></div>

<div id="blurbs_table_items" style="display:none;">
    <div class="item">
        <div class="blurb">jQuery Rocks</div>
        <div class="menu"></div>

    <div class="button view">view</div>
    <div class="button buy">buy</div>
    <div class="button info">info</div>
    <div class="button remove">remove</div>

The Solution

Here are a few assumptions we are going to make for this solution:

<script type="text/javascript">
    function addItem()
        //AJAX call to server, get back some JSON response
        var response = {item: {blurb: "This is a great example!"}}


    function removeItem(item)
        //AJAX call to server, get back some JSON

    function loadItems()
        //AJAX call to server, get JSON array of items
        var items = response.items;

        for(var item in items) appendItem(items[item]);

    function appendItem(item)
        var builder = $('#blurbs_table_items');
        var newItem = builder.children('.item').clone();
        var remove = builder
        .click(function(){ removeItem($(this).parents('.item')); });