Reputation: 5308
Here is an interesting problem. I have template like this.
<script id="temp" type="text/x-handlebars-template">
<div class="entry">
<label>Label 1 <input type="text" value="{{val1}}"/></label>
</div>
<div class="entry">
<label>Label 2 <input type="text" value="{{val2}}"/></label>
</div>
<div class="entry">
<label>Label 3 <input type="text" value="{{val3}}"/></label>
</div>
<div class="entry">
<label>Label 4 <input type="text" value="{{val4}}"/></label>
</div>
<div class="entry">
<label>Label 5 <input type="text" value="{{val5}}"/></label>
</div>
<div class="entry">
<label>Label 6 <input type="text" value="{{val6}}"/></label>
</div>
....
.... </script>
My template is pretty big. As i have shown above it has lot of inputs and i have included almost 10 bootstrap datetimepicker in my template. First time it is ok to compile and add dom like this.
var t = Handlebars.compile($('#temp').html());
$('body').append(t(values);
but it is not good to re-render this entire template when i need to update only input and datetime pickers value. So i need to do something like below, which should update values alone.
t(valueChanged);
OR
t('refresh', valueChanged);
Is there a way to do this? This jsFiddle may help you.
Upvotes: 0
Views: 1678
Reputation: 1994
You need a template like this:
<script type="text/template" id="list-item">
<label> <%= data.label %> <input type="text" value="<%= data.val %>"/></label>
</script>
Then use a backbone view like this:
var app = app || {};
// Item View
// --------------
app.ItemView = Backbone.View.extend({
tagName: 'div',
className: 'entry',
template: _.template( $('#list-item').html() ),
initialize: function() {
this.listenTo(this.model, 'change', this.render);
this.listenTo(this.model, 'destroy', this.remove);
},
render: function() {
this.$el.html( this.template( {data : this.model.attributes} ) );
return this;
},
clear: function() {
this.model.destroy();
}
});
Then use a collection to create/update a list of items.
Upvotes: 1