问题
This shouldn't be too hard.
I have a datepicker UI widget, and each time the user clicks on a month, I want to add or remove that month from the MonthsController
(an ArrayController
). The MonthsController
is not associated with a route, so in my ApplicationTemplate
I simply have
{{render months}}
A simplified version of my datepicker view is
App.DatepickerView = Ember.View.extend({
click: function(e) {
var id = $(this).datepicker().data('date').replace(" ", "-");
this.get('controller.controllers.months').toggleMonth(id);
}
});
and I handle the event in my MonthsController
:
App.MonthsController = Ember.ArrayController.extend({
toggleMonth: function(id) {
var month = App.Month.find(id),
index = this.indexOf(month);
if (index === -1) {
this.pushObject(month);
} else {
this.removeAt(index);
}
}
});
I thought I had this working, but then I realized that month
in the last snippet wasn't really an App.Month
, it was just (I suppose) an anonymous object.
How can I programmatically add/remove models to a controller?
回答1:
Your App.Month.find(id)
will return a promise
. If that month hasn't loaded yet you would also be loading this data from the server. You need to wrap your code in the promise's then
.
toggleMonth: function(id) {
var _this = this;
App.Month.find(id).then(function(month) {
var index = _this.indexOf(month);
if (index === -1) {
_this.pushObject(month);
} else {
_this.removeAt(index);
}
});
}
来源:https://stackoverflow.com/questions/17891718/how-can-i-programmatically-add-remove-models-to-a-controller