Reputation: 399
var app = {};
var FoodModel = Backbone.Model.extend({
url: "http://localhost/food"
});
var FoodCollection = Backbone.Collection.extend({
model: FoodModel,
url: "http://localhost/food"
});
var FoodView = Backbone.View.extend({
render: function(){
console.log(this.model.toJSON());
}
});
app.FoodModel = new FoodModel();
app.FoodCollection = new FoodCollection;
app.FoodCollection.fetch();
var myView = new FoodView({model: app.FoodModel})
In this piece of code, the console.log always returns null for data in this.model
If console.log the collection it is full of data, how can i get this.model inside the view to reflect the data in the collection?
Upvotes: 0
Views: 693
Reputation: 14923
I'm not sure where your app is triggering FoodView.render()
. It won't happen automatically when you instantiate FoodView
and it won't happen when the json response triggers a callback to app.FoodCollection.fetch()
unless you are manually calling that in a success
callback. If you are doing this, your context may have been lost.
Also, there are a few typos in your code (app.FoodCollection = new FoodCollection();
). If not, then can you provide the exact code? Please include whatever code is calling render()
Also, I'm not sure your view is being associated with your model. Try:
var FoodView = Backbone.View.extend({
model: FoodModel,
render: function(){
console.log(this.model.toJSON());
}
});
Otherwise, Backbone has no way of knowing what model you are referring to.
Upvotes: 1