Fred Thomas
Fred Thomas

Reputation: 217

JQuery Tmpl and Databinding working together

I am trying to get data binding and tmpls - the jquery plugins to work together well. So I want to use a template to render the data, and then data binding to hook it back into my objects. For example:

var items = [{ Name: 'Barak Obama', Phone: '555-1212' },
             { Name: 'George Bush', Phone: '444-2222'}];

function addItems() {
    $("MyList").html("");
    for (var index in items) {
        $("#ListTmpl").tmpl(items[index]).link(items[index]).appendTo("#MyList");
    }
};

With the template like this:

<script id="ListTmpl" type="text/x-jquery-tmpl">
    <li>
        <input id="Name" value="${Name}" />
        <input id="Phone" value="${Phone}" />
    </li>
</script>

However, where I have a problem is that I want item to contain an array, and render than with {{each}}

var items = [{ Name: 'Barak Obama', Phone: '555-1212',
             kids: [{Name: "Malia"}, {Name: "Sasha"}] },
             { Name: 'George Bush', Phone: '444-2222'},
             kids: [{Name: "Barbara"}, {Name: "Jenna"}] }];

and a template like this:

<script id="ListTmpl" type="text/x-jquery-tmpl">
    <li>
        <input id="Name" value="${Name}" />
        <input id="Phone" value="${Phone}" />
        <ul>
        {{each kids}}
           <li> ${Name}
        {{/each}}
        </ul>

But how do I get the kids names data linked back to the original objects?

Upvotes: 1

Views: 942

Answers (2)

Alexander Taran
Alexander Taran

Reputation: 6725

You might want to look at knockout.js
It does use jquery templates and it's own binding mechanism.

Upvotes: 1

Derek
Derek

Reputation: 589

.link() doesn't currently support nested arrays or objects like you are looking for. You will most likely want to flatten out your JSON object to take advantage of datalinking: http://jsfiddle.net/rUrXF/1/

It looks like there is an issue open for nested objects: https://github.com/jquery/jquery-datalink/issues/24

Upvotes: 0

Related Questions