Data Binding Solution for jQuery

August 19, 2008 at 1:01 am

I am proud to announce the first release of my new project called chain.js. But before we continue, I would like to write some introduction to data binding. ;p

If you want to skip this article and go directly to the wiki, click here

Data binding is an important part of our life as developer. Our job is to feed the users with data in a way so that they can work with it.

In the Server Side Age this binding is done in the server, usually using templates.

<div class="contact">
	<div><?php echo $name ?></div>
	<div><?php echo $address ?></div>

Nowadays, in Ajax world, we move all of this to the client side and with only one scripting language: javascript. Javascript doesn’t provide tool for binding data to html efficiently (not mentioning E4X). Still there are some ways to do this.

Using Templates

With the help of javascript libraries, you can do templates to bind your data to html.

var template = "<div class='contact'><div>{name}</div><div>{address}</div></div>";
var templateFunction = parseTemplate(template)
document.getElementById('container').innerHTML = templateFunction(data);

This method can be considered as the fastest way to generate content, since the innerHTML method is very fast. The real disadvantage of it is that it doesn’t play well with event. You can attach event to the generate content, but whenever the data changes, the whole content needs to be refreshed and the attached events will be lost.

The DOM Way of Life

A better method to bind data to the html is using DOM. With DOM you can manipulate the html using various DOM methods. This way, you can work with the various DOM events and use the interaction capabilities it offers and make your web application feels more dynamic.
However , there are some hassles of doing it this way. First, there are some incompatibilities between browsers and sometimes it can get very complex and ugly.

var contact = document.createElement('div');
contact.className = 'contact';
var name = document.createElement('div');
name.innerHTML =;
var address = document.createElement('address');
address.innerHTML = data.address;

Fortunately there are some great javascript libraries like jQuery.

$('<div class="contact"><div class="name"/><div class="address" /></div>')

But still, it gets repetitive if you have a lot of modules.

The solution I came up with for this problem is chain.js.
Chain.js provides automation service for this kind of tasks, and spare you from repetitive tasks.

$('<ul><li><span class="library" /></li></ul>')

Chain.js isn’t just bind data automatically to your HTML, but it also maintains and manages your data/items.

var data = {first:'Stephen', last:'Hawking'};
// Add one item
$('#persons').items('add', data);
// Remove item
$('#persons').items('remove', data);

Chain.js updates the View automatically (and in an efficient way) each time you add or remove data.
And the best of it is that your event won’t be gone during the updates.

$('<div><div class="name">Name</div><div class="address">Address</div></div>')
    .item({name:'Steve Jobs', address:'Cupertino'})
        this.bind('click', function(){
            var data = this.item();
            alert('name:'', address:'+data.address);

and of course there are many more features. just visit the wiki page

13 Commentsrss »

  • August 21, 2008
    9:42 pm

    love your plugin chain.js - the api is pretty straight-forward.
    thanks for the great work and greetings from rhineland-palatine ;)

  • August 22, 2008
    8:49 am

    Excellent! Thanx for that :)

  • August 22, 2008
    11:49 pm


    I’ve been using chain to some really cool stuff - basically advancing the demos you have - and I love it! But I’m not convinced I’m even scratching the surface of what it is capable lol.

    I have a problem tho and I can’t find the answer:

    Basically I do $(’#tbl-body’).items(items).chain();

    But then I want to change remove the whole chain functionality, update the html ‘template’ markup dynamically (I’m doing this), and then reapply chain with a new set of items.

    The bit I’m having trouble with is removing chain and the ‘buffer’ of content it stores behind the scenes - coz at the moment when I apply the new ‘items’ it is creating the right number of rows, but still using the old html ‘template’.

    Any ideas?

  • August 23, 2008
    2:11 am

    Are the items still the same, or do they need to be replaced as well?
    If you are having two templates, why don’t you simply put it in one template, and hide or show it when necessary? Can you please be more specific and give me some code examples? Please discuss this in the google group.

  • August 26, 2008
    6:59 am

    I’ve got a post at with 3 examples of binding data to table and how to create advanced custom data binding.

    Hope you like it.

  • August 28, 2008
    6:21 pm

    There is another templating solution called jsRepeater. This solution provides hierarchical databinding, advanced alternation and recursive templates (without the need for sub templates).

    Of course it’s 1.) Open Source, 2.) jQuery plugin and 3.) Free

    See if it might be useful for you:

  • August 28, 2008
    8:29 pm

    Please read the article, before posting comment about templating.

  • Marc D
    September 4, 2008
    7:29 pm

    This is exactly what I was looking for - a way to keep presentatation and data separate in client code, nice work!

    Is there a way to clear the previously bound items -> items(’clear’) ?


  • July 14, 2009
    4:07 pm

    Hi, really nice plugin, data binding is something that must be better in DOM.

    Is there an example using chain.js and html 5 storage?
    I’m really interesting saving and retrieving data from browser’s storage and binding to a element.


  • February 16, 2017
    10:48 am

    Я делюсь секретами заработка в интернете и досконально все
    расписываю на моем секретном сайте:

    Информация для поисковых систем: самый легкий СЃРїРѕСЃРѕР± заработать РІ интернете 4 буквыкакие СЃРїРѕСЃРѕР±С‹ заработать интернете qiwiРёРіСЂС‹ РіРґРµ зарабатывают реальные деньгизаконный заработок интернете byflyкак быстро заработать деньги одесса, как заработать РЅР° покере РІ интернете zoomgorod ruзаработок РІ интернете РЅР° кликах лучшие сайтызаработок РІ интернете для новичков Рё начинающих 36 картзаработок РЅР° фотографиях без вложений 756$ РІ месяцищу заработок без вложений zima, прилично заработать интернете 4 буквысайты можно заработать интернете 2016дополнительный заработок РІ СЃРІРѕР±РѕРґРЅРѕРµ время без вложений outlookкак неплохо заработать РІ интернетекак заработать РІ интернете без вложений Рё регистрации РїСЂСЏРјРѕ сейчас.

  • Dennisornaw
    February 27, 2017
    1:06 am

    Zhheherhrh eg egemtr hrggwe wes egemtrghdfbsgd rwtwrqw

  • Larrypop
    March 2, 2017
    5:51 pm

    Бильярд онлайн бесплатно, играй и получай удовольствие.
    Бильярд онлайн это потрясающая игра которая подойдет абсолютно всем независимо от возраста.

  • May 5, 2017
    7:46 am

    Cialis Generika Gefahrlich Acheter Viagra Sans Ordonnance Apotheke Kamagra Cialis Auf Rechnung Bentyl 20mg In Internet Viagra Generico Farmacia Andorra viagra Vip Transaction Pharmacy Priligy Sin Receta Andorra Dental Cellulitis Keflex Purchase Isotretinoin Price In Internet Caracteristicas Propecia

Leave a comment