如何以编程方式将模型添加到控制器? [英] How can I programmatically add/remove models to a controller?

查看:102
本文介绍了如何以编程方式将模型添加到控制器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这不应该太难了。

我有一个datepicker UI小部件,每次用户点击一个月,我想添加或删除月份从 MonthsController (一个 ArrayController )。 MonthsController 不与路由相关联,所以在我的 ApplicationTemplate 中,我只需要

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}}

我的datepicker视图的简化版本是

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

我处理我的 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 <最后一个片段中的code>并不是一个真正的 App.Month ,只是(我想)一个匿名对象。

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?

推荐答案

您的 App.Month.find(id)将返回 promise 。如果那个月还没有加载,你还将从服务器加载这些数据。您需要将您的代码包裹在承诺的然后中。

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

这篇关于如何以编程方式将模型添加到控制器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆