Shivam
Shivam

Reputation: 2248

Change underscore.js template variable on the go

I want to update the value on the template variable so it changes if a user clicks it, it would change the data on the page.

<script type="text/template" id="graph-template">
<% _.each(results, function(results) { %>
     <ul class="barGraph">
        <li>
            <div class="left"><p><%= results.title %></p></div>
            <div class="right">

            <!-- THIS SHOULD CHANGE TO results.views if I statement is true without reloading data -->
            <span class="bar" style="width: <%= Math.floor(results.totalCount / 1000) %>%;">
                Total Views: <%= results.totalCount %>
            </span>
            <!-- THIS SHOULD CHANGE TO results.views if I statement is true -->

            </div>
        </li>
     </ul>
<% }); %>
</script>


$('input[name="views"]').change(function(e) { 
    if( $(this).val() == 'total') {
        resultsTemplating(sortByCount);
    } else {
        resultsTemplating(sortByAverage);
    }
});

Upvotes: 2

Views: 700

Answers (1)

Dmitry Shurshilin
Dmitry Shurshilin

Reputation: 766

In that case I would add some IDs for each item in the results collection and update items by them. And after any changes template should be updated with new data and inserted again.

This is an example with click, but you can change it

var results = [
    { id: 1, title: 'Some title', totalCount: 2},
    { id: 2 ,title: 'Another title', totalCount: 3},
    { id: 3, title: 'Another title', totalCount: 4}
];

var compiled = _.template($('#graph-template').html());
$('#app').html(compiled({results: results}));

$('body').on('click', '.js-value', function() {
    var $el = $(this);
    _.each(results, function(item) {
        if (item.id == $el.data('index')) {
            item.totalCount += +$el.attr('value');
        }
    });
    results = _.sortBy(results, 'totalCount');
    $('#app').html(compiled({results: results}));
});

And see fiddle http://jsfiddle.net/shurshilin/kxk1Lhkf/1/

Feel free to ask if you have any questions because maybe I understood your question incorrectly.

Upvotes: 1

Related Questions