如何以编程方式将模型添加/删除到控制器?

时间:2013-07-26 22:00:22

标签: ember.js

这不应该太难。

我有一个datepicker UI小部件,每次用户点击一个月时,我都希望从MonthsControllerArrayController)添加或删除该月份。 MonthsController与路线无关,因此在我的ApplicationTemplate我只有

{{render months}}

我的datepicker视图的简化版本是

App.DatepickerView = Ember.View.extend({
    click: function(e) {
      var id = $(this).datepicker().data('date').replace(" ", "-");
      this.get('controller.controllers.months').toggleMonth(id);
    }
});

我在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);
        }
    }
});

我以为我有这个工作,但后来我意识到最后一个片段中的month不是真正的App.Month,它只是(我猜)是一个匿名对象。

如何以编程方式向控制器添加/删除模型?

1 个答案:

答案 0 :(得分:2)

您的App.Month.find(id)将返回promise。如果该月尚未加载,您还将从服务器加载此数据。您需要将代码包装在promise 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);
    }
  });
}