如何在一个视图中使用多个 ember 数据模型

Posted

技术标签:

【中文标题】如何在一个视图中使用多个 ember 数据模型【英文标题】:how to use multiple ember data models in one view 【发布时间】:2013-01-12 14:41:37 【问题描述】:

鉴于 RESTful 服务器上的这些 JSON 数据模型

/用户

"users":[
   "id":"1","first_name":"John","last_name":"Doe",
   "id":"2","first_name":"Donald","last_name":"Duck"
]

/users/1

"user": 
   "id":"1","first_name":"John","last_name":"Doe","account":"1"

/帐户

"accounts":[
   "id":"1","owned_by":"1","id":"2","owned_by":"2"
]

/accounts/1

"account":
   "id":"1","owned_by":"1","transactions":[1,17]

还有这些 Ember 数据模型

App.Store = DS.Store.extend(
  revision: 11,
  adapter: DS.RESTAdapter.create(
    url: 'http://api.mydomain.ca'
  )
);

App.User = DS.Model.extend(
    firstName: DS.attr('string'),
    lastName: DS.attr('string'),
    account: DS.belongsTo('App.Account')
);

App.Account = DS.Model.extend(
    ownedBy: DS.belongsTo('App.User'),
    transactions: DS.hasMany('App.Transaction')
);

我还需要编写哪些其他 ember 代码才能将数据加载到模型中,然后编写一个模板来输出用户名、帐户 ID 和帐户中的交易数量?

【问题讨论】:

【参考方案1】:

我能够解决这个问题,所以我会发布我的代码以防它帮助其他人。诀窍是确保 JSON 数据的格式与 Ember 想要的完全一致,并创建正确的路由。

据我所知,Ember 期望父对象提供子对象列表。这对我来说感觉很奇怪,所以如果有人知道用外键引用其父母的子对象的方法,请告诉我。

我将 /user/:user_id JSON 对象上的帐户属性更改为 account_id 我还在 /users 中找到的用户对象中包含了 account_id,并将帐户上的owned_by 属性更改为 user_id。

我的 javascript 文件

var App = Ember.Application.create();

// Router
App.Router.map(function() 
    this.resource('users', function() 
        this.resource('user', path:':user_id');
    ); // '/#/users/:user_id'
    this.resource('accounts', function() 
        this.resource('account', path:':account_id');
    );
);

App.IndexRoute = Ember.Route.extend(
    redirect: function() 
        this.transitionTo('users');
    
);

App.UsersRoute = Ember.Route.extend(
    model: function() 
        return App.User.find();
    
);

App.AccountsRoute = Ember.Route.extend(
    model: function() 
        return App.Account.find();
     
);

// Controllers

App.TransactionsController = Ember.ArrayController.extend();

// Adapter
App.Adapter = DS.RESTAdapter.extend(
    url: 'http://api.mydomain.ca'
);

// Models

App.Store = DS.Store.extend(
  revision: 11,
  adapter: App.Adapter.create()
);

App.User = DS.Model.extend(
    firstName: DS.attr('string'),
    lastName: DS.attr('string'),
    account: DS.belongsTo('App.Account')
);

App.Account = DS.Model.extend(
    user: DS.belongsTo('App.User'),
    transactions: DS.hasMany('App.Transaction'),
    balance: function() 
      return this.get('transactions').getEach('amount').reduce(function(accum, item) 
          return accum + item;
      , 0);
  .property('transactions.@each.amount')
);

App.Transaction = DS.Model.extend(
    account: DS.belongsTo('App.Account'),
    amount: DS.attr('number'),
    description: DS.attr('string'),
    timestamp: DS.attr('date')
);

还有车把模板

<script type="text/x-handlebars" data-template-name="application">
    <div class="row">
        <div class="twelve columns">
            <h2>Accounts</h2>
            <p>outlet</p>
        </div>
    </div>
</script>

<script type="text/x-handlebars" data-template-name="users">
    <div class="row">
        <div class="three columns" id="users">
            #each user in controller 
                #linkTo "user" user class="panel twelve columns"user.firstName user.lastName/linkTo
            /each
        </div>
        <div class="nine columns" id="user">
             outlet 
        </div>
    </div>  
</script>

<script type="text/x-handlebars" data-template-name="user">
    <h2>firstName lastName</h2>
    #if account
    render "account" account
    else
    Error: Account not set up!
    /if
</script>

<script type="text/x-handlebars" data-template-name="accounts">
    <div class="row">
        <div class="three columns" id="accounts">
            #each account in controller 
                #linkTo "account" account class="panel twelve columns"account.id account.user.firstName account.user.lastName/linkTo
            /each
        </div>
        <div class="nine columns" id="account">
             outlet 
        </div>
    </div>  
</script>

<script type="text/x-handlebars" data-template-name="account">
    <p>Account Number: id, Balance: balance, transactions.length transactions</p>
    render "transactions" transactions
</script>

<script type="text/x-handlebars" data-template-name="transactions">
    <table class="table table-striped">
        <thead>
            <tr>
                <th>ID</th>
                <th>Amount</th>
                <th>Timestamp</th>
                <th>Description</th>
            </tr>
        </thead>
        <tbody>
        #each transaction in controller
            <tr>
                <td>transaction.id</td>
                <td>transaction.amount</td>
                <td>transaction.timestamp</td>
                <td>transaction.description</td>
            </tr>
        /each
        </tbody>
    </table>
</script>

【讨论】:

【参考方案2】:

创建一个 Index 路由,为您的 IndexController 植入一个模型,并创建一个相关的模板来迭代您的关系。

下面是 post 和 cmets 之间的简单 HasMany-Relationship 示例:

var App = Ember.Application.create();
App.Store = DS.Store.extend(
  revision: 11,
  adapter: DS.RESTAdapter.create()
);

App.Post = DS.Model.extend(
  comments: DS.hasMany('App.Comment')
);
App.Comment = DS.Model.extend(
  post: DS.belongsTo('App.Post'),
  body: DS.attr('string'),
);

App.IndexRoute = Ember.Route.extend(
  setupController: function(controller) 
    controller.set('content', App.Post.find("1"));
  
);

html 代码应如下所示:

<!DOCTYPE html>
<html>
<head>
  ...
</head>
<body>
  <script type="text/x-handlebars" data-template-name="index">
  #each comment in content.comments
    comment.body
  /each
  </script>
</body>

最后但并非最不重要的服务器响应 /posts/1


"post": 
"id": 1,
"title": "Rails is omakase",
"comments": [1, 2, 3]
,

"comments": [
"id": 1,
"body": "But is it _lightweight_ omakase?"
,

"id": 2,
"body": "I for one welcome our new omakase overlords"
,

"id": 3,
"body": "Put me on the fast track to a delicious dinner"
]

【讨论】:

以上是关于如何在一个视图中使用多个 ember 数据模型的主要内容,如果未能解决你的问题,请参考以下文章

Ember - 在视图中显示模型数据

如何在 Ember JS 中获取模型数据

如何在 Ember 中(重新)渲染视图模板时收到通知?

如何在 EmberJS / Ember Data 中使用单个路由的多个模型?

在 ember 中,如何将视图数据从拖放中传递?

如何在Ember中使用模型在页面之间传送一些数据?