I have a Backbone view that renders a calendar, which in turn renders a sub-view for each day. Each day has a single model and a single click event that either selects or de-selects the day. If a day is selected, the model is saved, and if it's de-selected, the model is destroyed.
Once a view's model is destroyed (because the date was de-selected), I'm not sure how to save a new model in the collection of calendar dates if the date is re-selected. The view only knows about the model — nothing about the collection. Should the calendar view handle creating and attaching a new model to the date view when the model is destroyed? Or should the date view be passed the collection and do that on its own? Or is there a better solution?
Here are some snippets of my code for clarity:
var CalendarView = Backbone.View.extend({
initialize: function () {
this.model.dates.on('reset', this.renderDates, this);
},
renderDates: function () {
// Loop through the number of days to display and create a view for each.
// Find a model for the date. If one doesn't exist, this returns a new model.
model = this.model.dates.completedOn(date.format('YYYY-MM-DD'));
view = new DateView({
model: model
});
$dates.append(view.render().el);
// End loop.
}
});
var DateView = Backbone.View.extend({
events: {
'click .date': 'toggleDate'
},
toggleDate: function () {
if (this.model.selected()) {
this.model.destroy();
}
else {
this.model.save();
}
}
});
Thanks for any help!