I have a straightforward REST API that provides information about an item at /api/items/:id
, which includes the ID and name. I am using a Router to organize my Backbone views. The edit
route creates a FormEditItem view, passing the ID from the URL.
To retrieve the data for the model from the API, the form view creates a new model, sets the ID, and then calls the model's fetch method. (This approach was recommended in this thread.)
The model declaration is very simple:
App.Models.Item = Backbone.Model.extend({
urlRoot: 'api/items'
});
This is my form view:
App.Views.FormEditItem = Backbone.View.extend({
template: _.template($('#tpl-formEditItem').html()),
initialize: function(opts) {
_.bindAll(this, "render");
this.modelID = opts.modelID;
this.parent = opts.parent;
this.model = new App.Models.Item({id: this.modelID});
this.model.fetch();
this.render();
},
render: function() {
console.log('Starting render:', this.model);
console.log(this.model.get('name'));
this.parent.$el.append(this.template(this.model.toJSON()));
return this;
}
});
In the render function of my form view, I am logging the model. I can see the model's attributes. However, when I try to log the results of get('name') on the next line, it returns as undefined!
What could be causing this issue? Do I need to define a model's attributes before fetching them from the database?
=============================================================================
EDIT
Following Stephen and Rida's advice, the solution in this case is to add an event listener to the model's change
event. The fetch
operation takes some time to retrieve the data from the API: I was trying to display the data before it was available. Therefore, my initialize function should look like this:
initialize: function(opts) {
_.bindAll(this, "render");
this.modelID = opts.modelID;
this.parent = opts.parent;
this.model = new App.Models.Item({id: this.modelID});
this.listenTo(this.model, 'change', this.render);
this.model.fetch();
}
Thank you, everyone!