Toshi
Toshi

Reputation: 23

How to fetch and console json date on Backbone.js

I am trying to pull JSON data and display on my console just to see if its working. I am seeing an error message.

I am trying to fetch a Model with id 1:

var TeamModel = Backbone.Model.extend({
  urlRoot: '/json/team.json'
});

//Create Team Model Instance with id of team
var teamModel = new TeamModel({
  id: 1
 });

//Fetch the json data
teamModel.fetch();
var director = teamModel.get('name');

Here is the JSON file :

{
    "id" : 1,
    "name" : "Sam",
    "img_small" : "images/sam.jpg",
    "location" : "NYC",
    "role" : "Director, Producer, & Writer",
}

This yields the following error :

GET http://localhost:9000/json/team.json/1 404 (Not Found)

Upvotes: 0

Views: 80

Answers (1)

joews
joews

Reputation: 30330

You should use url, not urlRoot:

var TeamModel = Backbone.Model.extend({
  url: '/json/team.json'
});

Backbone uses urlRoot to generate resource URLs based on the operation you perform (fetch, save, delete) and Model id. When you fetch a single Model, the URL it generates is urlRoot + '/' + id.

Therefore when you attempt to fetch a Model with id 1, the constructed URL is /json/team.json/1

If you set url, however, Backbone always uses that url. It does not change it based on operation or model attributes. This is the behaviour that you need, because you have a single static resource.

Upvotes: 1

Related Questions