문제

This might be and obvious questions, however I'm not seeing any documentation that directly addresses the how backbone prefers JSON to be formatted from a REST API source.

Ideally I would like to reduce the number of API calls by including inside the post and a few of the most recent comments.

For instance

Say I were retrieving post number 404. Using a GET to http://api.example.com/v1/posts/404.json using .get(404)

I would think a nested JSON would be convenient/clean:

{
    "id": 404,
    "title": "Hans shot first.",
    "comments": [
      {
        "id": 4041,
        "body": "But not anymore!"
      },
      {
        "id": 4042,
      "body": "Indeed he did."
      }
    ]
}

Ember.js seems to prefer using relational ids. source Does Backbone.js prefer similar?

{
  "post": {
    "id": 404,
    "title": "Hans shot first.",
    "comment_ids": [4041, 4042]
  },

  "comments": [{
    "id": 4041,
    "body": "But not anymore!"
  },
  {
    "id": 4042,
    "body": "Indeed he did."
  }]
}

I found related posts at Backbone.js restful json API design, and Backbone.js & REST API resources relationship & interraction, among others. However they lack examples of the actual internal JSON structure recommendations. Backbone Fundamentals

도움이 되었습니까?

해결책

I don't believe Backbone.js has any preference one way or the other. The way your JSON is structured is left entirely up to you. The first example works well if you're not expecting the comment data to outweigh the rest of the post's data. But if you're making something like Reddit where the number of comments is more than the number of characters in the entire post body, the relational structure is much friendlier to work with.

Backbone.js doesn't care how you structure your data because it leaves parsing and rendering the data entirely up to you. So pick the structure that fits your needs for the task at hand.

One thing I would change in the first example is removing the pointless "post" object wrapper:

{
    "id": 404,
    "title": "Hans shot first.",
    "comments": [
      {
        "id": 4041,
        "body": "But not anymore!"
      },
      {
        "id": 4042,
      "body": "Indeed he did."
      }
    ]
}

다른 팁

In backbone, currently I will recommend to use a single object or a collection of object. For the example above I will recommend to fetch the post and comment collection separately. If you want to use the JSON mentioned above I think you should use backbone-relational (http://backbonerelational.org/) which solves exactly the same problem.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top