Good morning, I have a simple json file and I need to fetch my data (I already read thousand of other question about it but not find a good solution for my app). I have a view, a model a json file. I can fetch my data but I can't display them. Here my code:
calendarDetails.json
{
"calendarTitle": "WebCal",
"calendarDescription": "Hello, I'm your new calendar"
}
HeaderModel.js
var HeaderModel = Backbone.Model.extend({
isEdit: false,
url: '/assets/calendarDetail.json'
});
headerModel = new HeaderModel();
headerModel.fetch();
HeaderView.js
var HeaderView = Backbone.View.extend({
template: HandlebarsTemplates["header"],
model: headerModel,
initialize: function(){
this.render();
this.model.on('change', this.render, this);
},
render: function(){
this.$el.html(this.template(this.model.toJSON()));
return this;
}
});
app.js
$(function() {
var CalendarApp = Backbone.View.extend({
el: $('#wrap'),
initialize: function(){
this.headerModel = new HeaderModel();
this.headerView = new HeaderView({
model: this.headerModel,
el: $('header')
}),
this.monthView = new MonthView({
el: $("#calendarView")
})
}
});
var calendar = new CalendarApp;
});
I'm working with RubyonRails and Handelbars
Any help is really appreciated!!
You have to fetch your model :
$(function() {
var CalendarApp = Backbone.View.extend({
el: $('#wrap'),
initialize: function(){
this.headerModel = new HeaderModel();
this.headerView = new HeaderView({
model: this.headerModel,
el: $('header')
}); // semicolon here
this.headerModel.fetch(); // Here
this.monthView = new MonthView({
el: $("#calendarView")
}); // semicolon here
}
});
var calendar = new CalendarApp;
});
Your problem is that in your HeaderModel.js
you are instantiating your model and fetching it, so your model will be populated with your json file and that's it.
In your HeaderView.js
your are affecting your model to the view class, nothing more, the view initialize
and render
functions are not yet called.
In your app.js
when you instantiate your view
this.headerView = new HeaderView({
model: this.headerModel,
el: $('header')
})
your are overriding the previously set model with a new one this.headerModel
so when the initialize
and render
are executed your new model this.headerModel
is empty.