Reputation: 11104
This is a very basic question on how to get started using templates. This is literally my first time using backbone so any additional pointers on how to improve my code are appreciated:
example is here: http://jsfiddle.net/H93Ej/12/
for the following snippet:
addFurnitureLi: function (model) {
// Add a new piece of furniture to the DOM list
$("#furniture-list").append("<li>" + model.get('name') + "</li>");
}
I would like to go from using append()
to using a template like this:
<script id="furnitureTemplate" type="text/html">
<li>{{ name }}</li>
</script>
But I'm lost as to how to integrate the above script template into the addFurnitureLi
function. Also, I feel as though essentially the addFurnitureLi
function is "rendering" HTML on the page, so I have another question-- what is the difference between that function and an "official" render
function?
Thank you for educating me!
Full app code is listed below:
(function($) {
Furniture = Backbone.Model.extend({
defaults: {
"name" : null,
"quantity" : 1
}
});
Furnitures = Backbone.Collection.extend({
initialize: function (models, options) {
this.bind("add", options.view.addFurnitureLi);
//Listen for new additions to the collection and call a view function if so
}
});
FurnitureView = Backbone.View.extend({
el: $("body"),
initialize: function () {
this.furnitures = new Furnitures( null, { view: this });
},
events: {
"click .furniture-add": "addFurnitureModel",
},
addFurnitureModel: function (ev) {
// Add a piece of furniture to the model
var furnitureName = $(ev.currentTarget).data('name'),
furnitureModel = new Furniture({ name: furnitureName });
this.furnitures.add( furnitureModel);
},
addFurnitureLi: function (model) {
// Add a new piece of furniture to the DOM list
$("#furniture-list").append("<li>" + model.get('name') + "</li>");
}
});
var furnitureView = new FurnitureView;
})(jQuery);
Upvotes: 0
Views: 127
Reputation: 11104
Boom shakah-lakah.
given that the ID of your template script is furnitureTemplate
:
<script id="furnitureTemplate" type="text/html">
<li>{{ name }}</li>
</script>
This works fine:
addFurnitureLi: function (model) {
// Add a new piece of furniture to the DOM list
$('#furniture-list').append( ich.furnitureTemplate( model.toJSON() ) );
}
Upvotes: 1