Data Binding Solution for jQuery

admin
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.

1
2
3
4
<div class="contact">
	<div><?php echo $name ?></div>
	<div><?php echo $address ?></div>
</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.

1
2
3
4
5
6
7
8
var contact = document.createElement('div');
contact.className = 'contact';
var name = document.createElement('div');
name.innerHTML = data.name;
contact.appendChild(name);
var address = document.createElement('address');
address.innerHTML = data.address;
contact.appendChild(address);

Fortunately there are some great javascript libraries like jQuery.

$('<div class="contact"><div class="name"/><div class="address" /></div>')
	.find('.name').text(data.name)
	.end()
	.find('.address').text(data.address);

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>')
    .items([
        {library:'Prototype'},
        {library:'jQuery'},
        {library:'Dojo'},
        {library:'MooTools'}
    ])
    .chain();

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'})
    .chain(function(){
        this.bind('click', function(){
            var data = this.item();
            alert('name:'+data.name+', address:'+data.address);
        });

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

16 Commentsrss »

  • August 21, 2008
    9:42 pm

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

  • August 22, 2008
    8:49 am

    Excellent! Thanx for that :)

  • August 22, 2008
    11:49 pm

    Hey,

    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. http://groups.google.com/group/chainjs

  • August 26, 2008
    6:59 am

    I’ve got a post at JavaScriptly.com 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:
    http://jsrepeater.devprog.com/

  • 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’) ?

    Thanks

  • 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.

    Thanks

  • February 16, 2017
    10:48 am

    Я делюсь секретами заработка в интернете и досконально все
    расписываю на моем секретном сайте: http://1-million-rubley.xyz

    Информация для поисковых систем: самый легкий СЃРїРѕСЃРѕР± заработать РІ интернете 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

  • June 2, 2017
    7:21 pm

    ?Highest quality essay crafting services via the internet
    Have you always considered yourself as an academic tramp that does not have enough time and desire to write down an essay? Our finest essay crafting provider can return your favor to the academic society. Our team of professional instructors is prepared to solve your query about “Who will do my essay” and help you to definitely cope with any stage of academic disciplines. Our agency attracts and hires only professionals, experts in their scientific area and is willing to put in writing essay papers on any topic, any complexity. Every member of our team is a really universal essay helper and has everything you would like – desire, skills and knowledge.
    Several students think that tailor made essay crafting is actually a painless task for a student. However, its completion requires certain knowledge along with a lot of peculiarities. To successfully extensive this task, you should have to showcase creativity and express your individuality to understand the subject and watch style and grammar. This kind of do the job lies on the cross of artistic and journalistic branches.
    Our enterprise has the opportunity to deliver first-hand articles and provides solutions on how to compose an essay paper correctly. Each individual indigent student can buy essays using the net from us as a part of any discipline – history, literature, social studies, linguistics, at the same time as others.
    Our English essay writer will pleasantly surprise you!
    We do not perform that has a template! We do not have a “standard” proposal “for all customers”. Every procedure is unique given that we appreciate nearly everybody who came to us for help or advice. Therefore, we establish our function leaning only on your wishes and specifications for further successful procedures. Our essays for sale are not reuse or republish papers offered at decreased prices for coursework and diplomas. It means that that you just will pay out for essay those prices that correspond to the superior as a result of we estimate confidentiality policies, and while in the conclude, the do the job will be sent strictly on time according to your specifications! Typically, the very low price utilized to hide cheap, ready-made will work that are usually offered by various sorts of educational institutions, unreliable agencies or crooks!
    If you should order essay, coursework, diploma, or any other scientific get the job done from us – rest assured – it will be done for you individually! Our managers will calculate the expense and fully aid you every step, commencing with the earliest of your appeal to us! Those that haven’t yet decided to the choice of topic – we’ll help you get hold of a suitable and relevant idea to the essay. If you decide to do not have a proper plan – we are wanting to offer our reliable help and reasonable solutions.
    Our essay writers for hire and experts of all academic proficiencies are able to make a well-structured composition, with all corrections according to all academic standards, avoiding plagiarism and grammar mistakes. In order to ensure the top notch of our written papers, we engage in working proficient proofreaders and editors who will do their most advantageous to deliver you 100 original and high-quality papers.

    Incomparable College essay help is Provided Below

    Have you always struggling with the issue: “Who is able to jot down my essay?”? Cooperating with our experts, several strengths appear:

    Excellent high-quality papers

    Bestessay4you! – It will mean that your paper will be managed by a professional English essay writer so that while in the final result you will obtain a superior draft prepared efficiently and in the highest stage influenced by your specified requests.

    Certified Warranties

    Before beginning to keep up the order, you fill the order variety which formally becomes a contract with the guarantees of f-r-e-e maintenance and providing providers.

    Promptness in the get the job done

    Below you can actually buy essay accompanied by a term of execution from just one working day contingent on the type of required subject and perform complexity.

    Excessive uniqueness

    All of our essays are personalized made, tested by “anti-plagiarism” software and checked by our team of experts. The unique nature of each and every paper is much more than 99.
    Suitable and affordable prices
    With us it is easy to order cheap essays with ease.
    Every working day guidance
    A personal supervisor or writer is attached to each and every client so that the customer can monitor the creating course of action and if it necessary, help us with other materials. So, really do not hesitate to contact our assist team in order to get a suitable college essay help, clarify all the details, confirm the order and answer all your queries. They are always wanting to assist you and make your academic life easier and much more enjoyable.
    paper writing

  • June 16, 2017
    9:21 am

    Finasteride Effets Secondaires Prices Cialis Lowpricenonprescriptionviagra

  • транспортерная лента
    термостойкая лента резинотехнические резина техническая ремонт конвейерных лент конвейерная лента своими руками

    95qyqvo8BS

    35v 2705

Leave a comment