Once I create dom elements base on json data with jtemplates, what is the best way to reorder those elements based on changes to the json data (sorting, filtering, etc.).
-
Can you not sort the JSON stuff first, and then create the elements? – Pointy Feb 11 '10 at 17:01
-
Thanks @Jonathan. @Pointy, yes sorting the json data and creating the elements with jtemplates works fine. But afterwords, on the client, I want to be able to sort and filter the json data and reflect those changes on the dom elements by moving them around and showing/hiding them. – Ryan Feb 11 '10 at 17:24
3 Answers
So the method I'm using to solve this right now is I added a numbered index to each of my templated sections of html like so:
<div id="list">
<div id="items-start"></div>
{#foreach $T as item}
<div id="item-{$T.item$index}" class="item">
...lots of stuff...
</div>
{#/for}
</div>
Then in my json items I added an attribute called InitialIndex to keep track of which dom item is associated with each item in the json. This way after I make any changes to my json data I can call this simple function to apply the changes to the dom:
function applyListChanges(items) {
$('.item').hide();
for (var item in items) {
var index = items[item].InitialIndex;
$('#items-start').append($('#item-' + index));
$('#item-' + index).show();
}
}
Please let me know if you have a better solution.

- 73
- 7
The cleanest & easiest way of doing this would be as follows:
1) Re-order / sort your list of JSON objects 2) Clear the DOM list (or remove the list depending on your jTemplate), something like this
$('#list').html('');
3) Then re-populate the list by re-runing the jTemplate on the JSON object.
Keep in mind that rendering a list to the DOM using a templating engine is fast, makes your code much cleaner and doesn't require any complex logic to map JSON objects to their DOM equivalent

- 1,627
- 1
- 13
- 22
Create new element, add child elements to this element, add parent element to the DOM.

- 4,357
- 5
- 37
- 53