Mixin的参考控制器

时间:2013-10-08 08:37:31

标签: ember.js

一个简单的问题,我可以从ember中的mixin中获取对控制器的引用吗?

我有一个ApplicationController,我在其中设置通过ember-data检索的值,我想从Mixin中引用这些值。我找不到任何东西,所以我的假设是没有API吗?

App.Searchable = Ember.Mixin.create({
    search: function () {
        if (this.isValid()) {
            var controller = this.controllerFor('application');
            return controller.getProperties('fromDate', 'toDate', 'brokers', 'locations');
        }
        else
            return this.isInvalid;
    },
    isValid: function () {
        var controller = this.controllerFor('search');
        var fromDate = moment(this.get('fromDate'), 'YYYY-MM-DD');
        var toDate = moment(this.get('toDate'), 'YYYY-MM-DD');
        return moment(fromDate).isBefore(toDate) || moment(fromDate).isSame(toDate);
    },
    isInvalid: function () {
        $("#date-range-error").show();
    }
});

App.PnlRoute = Ember.Route.extend(App.Searchable, {
    model: function () {
        return this.store.find('pnl', this.search());
    },
    renderTemplate: function () {
        this.render('pnl', {
            into: 'application',
            outlet: 'data',
            controller: 'pnl'
        });
    },
    actions: {
        filter: function () {
            this.controllerFor('pnl').set('model', this.store.find('pnl', this.search()));
        }
    }
});

App.ApplicationController = Ember.ArrayController.extend({
    title: 'Pnl',
    fromDate: null,
    toDate: null,
    locations: [],
    ccyPairs: [],
    brokers: [],
    init: function () {
        var self = this;
        this.store.find('date').then(function (result) {
            var date = result.objectAt(0);
            self.set('fromDate', date.get('from'));
            self.set('toDate', date.get('to'));
        }), function (error) {
            $("#date-init-error").show();
        };
    }
});

1 个答案:

答案 0 :(得分:1)

在mixin中使用this.controllerFor('application')不起作用,因此你可以这样做的一种方法是将ApplicationController的引用存储在你创建的Mixin中的局部变量中,这样你以后就可以了轻松访问它。

例如:

App.ApplicationController = Ember.ObjectController.extend();

App.Searchable = Ember.Mixin.create({
  ctrl: null,
  search: function() {
    console.log(this.get('ctrl'));
  }
});

App.ApplicationRoute = Ember.Route.extend(App.Searchable, {
  activate: function() {
    this.set('ctrl', this.controllerFor('application'));
    this.search();
  }
});

示例jsbin:http://jsbin.com/ILeguSO/4/edit

希望它有所帮助。

相关问题