在没有路由的情况下实例化控制器和相关模型?

时间:2014-10-06 20:28:01

标签: ember.js

我正在构建一个应用程序,允许用户创建帐户并从网站所有者处获得个性化推荐。

我有一个SiteOwnerProfileController,用于使用SiteOwnerProfile模型的数据填充SiteOwner模板。我当然使用一条路线将这些连接在一起,并且它工作得非常好。

但是,我还需要使用SiteOwnderProfileController(由SiteOwner模型支持)来填充navbar模板。使用'需要' NavbarController上的属性允许我在{{controllers.siteOwnerProfile.fullName}}模板中使用navbar等帮助程序,但前提是用户已访问过具有用于连接的模型挂钩的SiteOwnerProfileRoute使用SiteOwnerProfileController模型SiteOwner

似乎最好的解决方案是直接在控制器上设置模型,以便在创建控制器实例时,模型可用。我尝试使用类似于{{render 'navbar' siteOwnerProfile}}的渲染助手,但似乎无法工作。

I've made a jsbin that illustrates the issue.

1 个答案:

答案 0 :(得分:0)

解决方案是使用应用程序路径检索SiteOwnerProfile数据并将其设置为SiteOwnerProfileController的模型。由于应用程序路径的钩子总是在其他路径的钩子之前执行,我们可以使用它来检索并为控制器分配模型。

添加以下内容使我的示例函数按预期运行:

App.ApplicationRoute = Ember.Route.extend({
  model: function () {
    return { fullName : 'siteOwnerName' };
  },

  setupController: function (controller, model) {
    this.controllerFor('siteOwnerProfile').set('model', model);
  }
});

Here's the jsbin with the solution added.

另外,如果您需要从应用程序路径提供多个模型,您只需从模型钩子返回一个哈希值,并在setupController中分配每个模型。例如:

App.ApplicationRoute = Ember.Route.extend({
  model: function () {
    return {
      siteOwnerProfileModel: {
        fullName : 'siteOwnerName'
      },
      customerModel: {
        name : 'Billy'
      },
      featuredProductModel: {
        type: 'T-shirt'
      }
    };
  },
  setupController: function (controller, model) {
    this.controllerFor('customer').set('model', model.customerModel);
    this.controllerFor('featuredProduct').set('model', model.featuredProductModel);
    this.controllerFor('siteOwnerProfile').set('model', model.siteOwnerProfileModel);
  }
});
相关问题