Reputation: 273
I'm following an app example from this repo and i started to build a similar app in my local machine using rails intead php for API, so i build apart the rails app in a specific root directory then in another root the backbone.js/JQM app calling rails api.
so i create the model and the collection in backbone with the urlRoot with: http://localhost:3000/api/clubs.json, that correspond to the local server url for retrieve a list of clubs
then i have tried to see in the javascript console what happen with these commands:
clubs = new ClubsCollection()
Object {length = 0 ...etc..}
clubs.fetch()
GET http://localhost:3000/api/clubs.json 200 OK
and the response is empty...
but when i call the url http://localhost:3000/api/clubs.json it returns the json clubs list correctly.
can you help me to understand the best way to do this call?
Upvotes: 0
Views: 1496
Reputation: 273
I have solved the problem using 'rack-cors' gem with the a basic config into
config/application.rb:
config.middleware.use Rack::Cors do
allow do
origins 'localhost'
resource '%r{/api/\$+.json}',
:headers => ['Origin', 'Accept', 'Content-Type'],
:methods => [:get, :put, :delete]
end
end
Upvotes: 1
Reputation: 620
If you look at the backbone API there is a success callback that you can provide with the fetch() call, e.g.
clubs.fetch({ success : function(model, err) { // do something } });
Like the other answer, fetch is asynchronous so you can't expect the results to be back by setting a break point after the .fetch() call.
Upvotes: 0
Reputation: 72868
fetch
is asynchronous. you have to wait for it to finish loading the data, and check the response then. This is typically done through the reset
event:
clubs = new ClubsCollection();
clubs.on("reset", function(){
alert(clubs.length + " item(s) found");
});
clubs.fetch();
Upvotes: 1