简体   繁体   中英

Handlebars: How to reuse template after dynamically updating array of objects

Okay so here is the the template I'm using

<script id='goalNavTemplate' type="text/x-handlebars-template">

 {{#each this}}
 <div class="bubble" data-dismiss="modal" data-Name="{{name}}"
 style="background:{{color}} url(images/{{icon}}IconSmall.png) 
 no-repeat 13px 14px;"></div>
 {{/each}}

</script>

And then I'm adding my objects in the array to the DOM with handlebars.

var template = Handlebars.compile($('#goalNavTemplate').html());
$('#selectGoalModal .modal-body').append(template(goals));

This works how I like, yet what I would like to do next is be able to update the DOM when a new object is added to the array (through user input). Yet if I call:

$('#selectGoalModal .modal-body').append(template(goals)); 

again it will add all the objects to the DOM and not just the last one. My current workaround is to remove the previously added elements and then use the above line of code after the array is updated. I was wondering if there is a more efficient way of doing this using handlebars? Like is there some way to bypass #each and just append the last object in the array? Would you use a helper? If so, how? Any insight into this would be awesome.

You can add some flags to goals item, eg datatime and check it by HB:

{{#each this.items}}
    {{#ifCond this.dt '>=' ../options.dt }}
        <div class="bubble" id="bub-{{id}}" style="background-color:{{color}};">        
            {{id}} - {{name}}
        </div>
    {{/ifCond}}
    {{#updateDOM "#bub-" id dt}}{{/updateDOM}}
{{/each}}

http://jsfiddle.net/2jvndb0L/5/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM