7.10 Models -- Handling Metadata(處理元數據)

1. 隨着從store中返回的records,你可能須要處理一些元數據。Metadata是伴隨着特定model或者type的一種數據,而不是record。服務器

2. 分頁是使用元數據的一個常見的例子。想象一個博客有比你一次能夠顯示的更多的posts。你可能會這樣查詢:post

let result = this.store.query("post", {
  limit: 10,
  offset: 0
});

3. 爲了獲得不一樣頁面的數據,你能夠簡單的改變offset爲10。到此爲止,一切尚好。可是你如何知道你有多少頁的數據?你的服務器須要返回records的總數做爲元數據的一部分。this

4. 每個序列化器將指望返回不一樣的元數據。例如,Ember Data的JSON反序列化器查找一個meta鍵:spa

{
  "post": {
    "id": 1,
    "title": "Progressive Enhancement is Dead",
    "comments": ["1", "2"],
    "links": {
      "user": "/people/tomdale"
    },
    // ...
  },

  "meta": {
    "total": 100
  }
}

5. 不管使用什麼序列化器,這個元數據是從響應中提取出來的。你能夠經過使用.get('meta')來讀取它。code

6. 這能夠在調用store.query()的結果中來完成:blog

store.query('post').then((result) => {
  let meta = result.get('meta');
})

7. 在belongsTo關係中:get

let post = store.peekRecord('post', 1);

post.get('author').then((author) => {
  let meta = author.get('meta');
});

或者在hasMany關係中:博客

let post = store.peekRecord('post', 1);

post.get('comments').then((comments) => {
  let meta = comments.get('meta');
});

8. 在讀取它以後,meta.total能夠被用於計算有多少頁。it

相關文章
相關標籤/搜索