Recently, I delved into the world of Backbone.js and currently, I am immersed in developing an app using Brunch that makes a JSONP request to an external API for populating my collection and models. Despite following guidance from previous posts (here and here) on handling JSONP requests with Backbone, my collection seems to not receive the data for some unknown reason.
In my model (app/models/model.js):
module.exports = Backbone.Model.extend({
});
And in my collection (app/models/collection.js):
var Post = require('./model');
module.exports = Backbone.Collection.extend({
model: Post,
url: "http://somedata.com/api/posts/list/stuff",
sync: function(method, model, options) {
options.timeout = 10000;
options.dataType = "jsonp";
options.jsonp = "JSONPcallback";
return Backbone.sync(method, model, options);
},
parse: function(response) {
if (response) {
var parsed = [];
for(var i = 0; i < response.results.length; i++) {
parsed.push(response.results[i][0]);
}
return parsed;
}
}
});
Then, within the initialize method in app/application.js, I call it as follows:
var Category = require('models/collection');
this.cat = new Category();
this.cat.fetch();
Upon inspecting the console log for the parse function, I can see that the data is indeed being fetched successfully. However, when the views are rendered and I execute console.log(application.cat.models) in app/views/view.js, nothing appears. Why is this happening? Could there be something amiss in the code for my model/collection?
Furthermore, the JSONP data adheres to the following format, which justifies looping through for response.results[i][0] and returning an array containing all of it - or so I thought:
{"results":[
{"0":{"id":xxx,"title":xxx,"link":xxx},
"description":xxx},
{"0":{"id":xxx,"title":xxx,"link":xxx},
"description":xxx},
{"0":{"id":xxx,"title":xxx,"link":xxx},
"description":xxx},...
]}
Your insights would be greatly appreciated...