Meteor iron-router中路由器的上下文变量

时间:2015-07-07 10:26:53

标签: javascript node.js meteor iron-router

ProjectController中有iron-router。我想确保project: Projects.findOne(this.params._id)在使用ProjectController的路线上的所有模板中都可用。

我怎样才能获得这个?现在我用

ProjectController = ApplicationController.extend({
  layoutTemplate: "projectLayout",
  waitOn: function () {
    return Meteor.subscribe('singleProject', this.params._id);
  },
  data: function () {
    return {
      project: Projects.findOne(this.params._id),
    }
  },
  action: function () {
    this.state.set('projectId', this.params._id);
    this.render();
  },
});

但是,在我设置data的新路线上,data中的ProjectController被覆盖,因此project模板变量不再可用。

1 个答案:

答案 0 :(得分:0)

一种解决方案可能是使用控制器为路由使用另一种自定义数据方法。例如,使用名为getData的方法,将其添加到控制器并在data方法中调用它:

ProjectController = ApplicationController.extend({
  layoutTemplate: "projectLayout",
  waitOn: function () {
    return Meteor.subscribe('singleProject', this.params._id);
  },
  getData: function () {
    return {};
  }
  data: function () {
    return _.extend({
      project: Projects.findOne(this.params._id)
    }, this.getData());
  },
  action: function () {
    this.state.set('projectId', this.params._id);
    this.render();
  },
});

然后在您的路线中使用getData代替data!它应该像魅力一样工作:getData将被覆盖(因为它只应该是控制器中的存根),并且将为真正的data方法提供所需的附加数据,将始终包含您的project对象。