Along with the records returned from your store, you’ll likely need to handle some kind of metadata. Metadata is data that goes along with a specific model or type instead of a record.

    与从仓库中返回的记录的同时,有时候需要处理一些元数据。元数据是除记录外,与特定模型类型一同的数据。

    Pagination is a common example of using metadata. Imagine a blog with far more posts than you can display at once. You might query it like so:

    分页是常见的一种元数据。例如一个博客拥有一次无法显示完的文章,那么就需要使用如下的查询:

    1. this.store.findQuery("post", {
    2. limit: 10,
    3. offset: 0
    4. });

    To get different pages of data, you’d simply change your offset in increments of 10. So far, so good. But how do you know how many pages of data you have? Your server would need to return the total number of records as a piece of metadata.

    为了获取不同页面的数据,只需要以10为增量来修改offset。到目前为止,一切都正常。现在有一个问题,就是如何知道拥有多少页数据呢?服务器需要以元数据的形式返回所有的记录数。

    By default, Ember Data’s JSON deserializer looks for a meta key:

    默认情况下,Ember Data的JSON反序列化会查找一个名为meta的键:

    1. {
    2. "post": {
    3. "id": 1,
    4. "title": "Progressive Enhancement is Dead",
    5. "comments": ["1", "2"],
    6. "links": {
    7. "user": "/people/tomdale"
    8. },
    9. // ...
    10. },
    11. "meta": {
    12. "total": 100
    13. }
    14. }

    The metadata for a specific type is then set to the contents of meta. You can access it with store.metadataFor:

    特定类型的元数据将被设置到meta中。可以使用store.metadataFor来获取。

    1. var meta = this.store.metadataFor("post");

    Now, meta.total can be used to calculate how many pages of posts you’ll have.

    现在meta.total可以用来计算拥有多少页文章了。

    You can also customize metadata extraction by overriding the extractMeta method. For example, if instead of a meta object, your server simply returned:

    此外,通过重写extractMeta方法,可以自定义元数据抽取的方法。例如,服务器没有使用meta对象来返回元数据,而是返回了下面的格式:

    1. {
    2. "post": [
    3. // ...
    4. ],
    5. "total": 100
    6. }

    You could extract it like so:

    那么可以这样来抽取元数据:

    1. App.ApplicationSerializer = DS.RESTSerializer.extend({
    2. extractMeta: function(store, type, payload) {
    3. if (payload && payload.total) {
    4. store.metaForType(type, { total: payload.total }); // sets the metadata for "post"
    5. delete payload.total; // keeps ember data from trying to parse "total" as a record
    6. }
    7. }
    8. });