Hey there, I'm currently working on setting up a simple SPA using Backbone for testing purposes. However, when I try to render my view, the Underscore template doesn't seem to be picking up any attributes from my model. I've been trying to troubleshoot this for quite some time now and could really use some guidance. In case it helps, I'm utilizing ASP.NET Web API 2, jQuery 2.x+, along with the latest versions of Backbone and Underscore.
Here's a snippet of my template:
<script type="text/template" id="equipmentTemplate">
<td><%= ID %></td>
<td><%= Name %></td>
<td><%= Quantity %></td>
<td><%= Description %></td>
</script>
This is how my code looks:
// Definition of a single item model
var EquipmentModel = Backbone.Model.extend({
urlRoot: '/api/equipment',
defaults: {
ID: '',
Name: '',
Quantity: '',
Description: ''
},
});
// Collection containing the single item models
var EquipmentList = Backbone.Collection.extend({
model: EquipmentModel,
url: '/api/equipment'
});
// Fetching a single instance of the model
var equipmentModel = new EquipmentModel({ id: 1 });
equipmentModel.fetch();
// Fetching the entire collection
var equipmentList = new EquipmentList();
equipmentList.fetch();
// Creating the view for a single model
EquipmentView = Backbone.View.extend({
tagName: "tr",
template: _.template($("#equipmentTemplate").html()),
render: function () {
this.$el.html(this.template(this.model.attributes));
}
});
var equipmentView = new EquipmentView({ model: equipmentModel });
equipmentView.render();
Upon calling console.log(equipment.fetch())
, the server returns the following response:
Object {readyState: 1, getResponseHeader: function, getAllResponseHeaders: function, setRequestHeader: function, overrideMimeType: function…}
// Response object details here...
However, despite the successful response from the server, when I check the content of equipmentView.$el.html()
, it shows empty table data elements.
I also attempted to include an actual model in the View but had no luck rendering the items. Even tried using this.model.toJSON()
. Here's one attempt:
EquipmentView = Backbone.View.extend({
tagName: "tr",
template: _.template($("#equipmentTemplate").html()),
render: function () {
this.$el.html('<td>'+ this.model.get('Name') + '</td>');
}
});
Unfortunately, that too just gives me an empty <td></td>
, which seems off.
Update: Figured it out, thanks to gerl.
I needed to fetch the model inside the view itself:
// Creating the view for a single model
EquipmentView = Backbone.View.extend({
initialize: function () {
this.model.fetch();
},
tagName: "tr",
template: _.template($("#equipmentTemplate").html()),
render: function () {
this.$el.html(this.template(this.model.toJSON()));
}
});
var equipmentView = new EquipmentView({ model: equipmentModel });
equipmentView.render();
And voilà, it worked like a charm!