How can I programmatically add/remove models to a controller?

拟墨画扇 提交于 2020-01-05 06:33:23

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!