【问题标题】:Using Backbone Relational to handle JSON-API Data使用 Backbone Relational 处理 JSON-API 数据
【发布时间】:2015-08-16 19:07:04
【问题描述】:

我们一直在使用 Backbone Relational 在前端建模我们的 ORM 关系,例如:

{
  id: 2
  username: "bob"
  comments: [
     {
        id:5,
        comment: "hi",
        user: {
           username: 'Bob'
        }
     }

  ]
}

在前端使用这样的模型效果很好:

  class User extends App.RelationalModel
    relations: [{
      type: Backbone.HasMany,
      key: 'comments',
      relatedModel: 'Comment',
      collectionType: 'CommentCollection'
    }]

但是现在我们的 api 发生了变化,并且更多地尊重 JSON-API 规范,因此来自后端的数据被封装在“数据”中。

{
  data: {
    id: 2
    username: "bob"
    data: {
      comments: [
         {
            id:5,
            comment: "hi",
            user: {
               username: 'Bob'
            }
         }
      ]
    },
    meta: {
    }
  }
}

我们如何指示骨干关系从 .data 中获取“cmets”关系的数据,而不是直接映射 json 结构?

对于''class User''我们可以像这样实现parse方法

class User
  parse: (response) ->
    response.data

但是我们如何为 cmets 关系做到这一点呢?

【问题讨论】:

    标签: json backbone.js backbone-model backbone-relational


    【解决方案1】:

    怎么样?

    parse: function (response) {
        var fixed_response = response.data;
        fixed_response.comments = fixed_response.data.comments;
        delete fixed_response.json.data;
        return fixed_response;
    }
    

    【讨论】:

      猜你喜欢
      • 2012-05-27
      • 1970-01-01
      • 2012-01-29
      • 1970-01-01
      • 2014-09-12
      • 2012-03-02
      • 2017-01-23
      • 2012-07-25
      • 1970-01-01
      相关资源
      最近更新 更多