1

我需要访问控制器属性以在我的 RESTAdapter 实例中构建自定义 URL,但我找不到在适配器上下文中访问控制器的方法。这是我所拥有的:

我有一个看起来像这样的简单模型:

App.Customer = DS.Model.extend(
{
    first_name:     DS.attr('string'),
    last_name:      DS.attr('string'),
    date_of_birth:  DS.attr('string'),
    created_at:     DS.attr('string'),
    updated_at:     DS.attr('string')
});

此模型的资源 REST URL 如下所示: https://api.server.com/v1/accounts/ :account_id /customers/ :customer_id

我正在为我的大多数模型扩展 Ember Data 中的 RESTAdapter,以便我可以单独自定义资源 URL。像这样:

App.CustomerAdapter = DS.RESTAdapter.extend(
{
    buildURL: function(type, id)
    {
        // I need access to an account_id here:
        return "new_url";
    }
});

如您所见,在此示例中,我需要 URL 中的帐户 ID 才能查询客户对象。帐户 ID 是用户必须通过登录提供的东西,并存储AccountControllerEmber.Controller.

我的问题是,如何从我AccountController的内部访问属性CustomerAdapter?以下是我尝试过的东西,没有一个有效:

App.CustomerAdapter = DS.RESTAdapter.extend(
{
    buildURL: function(type, id)
    {
        var account_id = this.controllerFor('account').get('activeAccount').get('id');
        return "new_url";
    }
});

,

App.CustomerAdapter = DS.RESTAdapter.extend(
{
    needs:                ['account'],
    accountController:    Ember.computed.alias("controllers.account"),

    buildURL: function(type, id)
    {
        var account_id = this.get('accountController').get('activeAccount').get('id');
        return "new_url";
    }
});

,

App.CustomerAdapter = DS.RESTAdapter.extend(
{
    activeAccountBinding = Ember.Binding.oneWay('App.AccountController.activeAccount');

    buildURL: function(type, id)
    {
        var account_id = this.get('activeAccount').get('id');
        return "new_url";
    }
});

在这一点上,我能想到的唯一技巧是将帐户 ID 放在 Ember 外部的全局变量中,然后在适配器中从那里访问它。

其他建议?

4

2 回答 2

1

我们有一个类似的问题,本质上我们做了一个全局变量,并为此感到内疚。我们的在 Ember 模型中,但存在相同的概念和问题。另一种解决方案是使用 findQuery,但这会返回一个集合,因此您必须将项目从集合中拉出。

App.CustomerAdapter = DS.RESTAdapter.extend(
{
    buildURL: function(type, id)
    {
        var params = type.params;
        return "new_url" + params.account_id;
    }
});

在某些路线中:

App.BlahRoute = Em.Route.extend({

   model: function(params){
      App.Customer.params = {account_id:123};
      this.get('store').find('customer', 3);
   }
});
于 2013-11-06T18:10:33.907 回答
0

我知道您可以在另一个控制器的上下文中访问控制器的属性。

我看到您尝试了一些类似的尝试,但无论如何这可能适用于适配器:

App.YourController = Ember.ObjectController.extend({
    needs: ['theOtherController'],
    someFunction: function () {
        var con = this.get('controllers.theOtherController');
        return con.get('propertyYouNeed');
    },
});

另外,您是否考虑过将 AccountId 属性添加到您的 Customer 模型中?

也许可以通过适当的路由实现自动 URL?

于 2013-11-06T22:00:56.937 回答