Reputation: 5812
I have two collections, my BlueCollection works fine loading data from an array stored in a variable, but my RedCollection has some problems fetching data from a different array which doesn't use a variable. Am I missing something?
BlueCollection = Backbone.Collection.extend({
model: BlueModel,
});
RedCollection = Backbone.Collection.extend({
model: RedModel,
url: 'data/data.json' // It is from http://www.localhost:3000/data/data.json
});
BlueCollection has no problems loading this data.
var blue = [
{id: 1, title: 'blue 1 - '},
{id: 2, title: 'blue 2 - '},
{id: 3, title: 'blue 3'}
];
But RedCollection has problems fetching this data
// http://www.localhost:3000/data/data.json
[
{id: 1, title: 'red 1 - '},
{id: 2, title: 'red 2 - '},
{id: 3, title: 'red 3'}
]
However, when I check firebug, I see that the browser receives the data, but fetch success
method never triggers, only complete
method triggers with the message parsererror
The full code is this:
var blue = [
{id: 1, title: 'blue 1 - '},
{id: 2, title: 'blue 2 - '},
{id: 3, title: 'blue 3'}
];
// http://www.localhost:3000/data/data.json
/* No variable, this json should be fetched from RedCollection
[
{id: 1, title: 'red 1 - '},
{id: 2, title: 'red 2 - '},
{id: 3, title: 'red 3'}
]
*/
BlueModel = Backbone.Model.extend({});
RedModel = Backbone.Model.extend({});
BlueCollection = Backbone.Collection.extend({
model: BlueModel,
});
RedCollection = Backbone.Collection.extend({
model: RedModel,
url: 'http://www.localhost:3000/data/data.json'
/*
[
{id: 1, title: 'red 1'},
{id: 2, title: 'red 2'},
{id: 3, title: 'red 3'}
]
*/
});
BlueView = Backbone.View.extend({
initialize: function() {
this.collection = new BlueCollection(blue);
this.render();
},
render: function() {
var self = this;
_.each(this.collection.models, function(item) {
self.addAll(item);
}, this);
},
addAll: function(item) {
$('#blue').append(item.get('title'));
}
});
RedView = Backbone.View.extend({
initialize: function() {
this.collection = new RedCollection;
this.collection.fetch({
success: function () {
console.log('Success'); // Never shows, but console shows content loaded
},
error: function(xhr, textStatus) {
console.log(xhr);
},
complete: function(xhr, textStatus) {
console.log(textStatus); // Only this log shows with: parsererror
}
});
this.render();
},
render: function() {
var self = this;
_.each(this.collection.models, function(item) {
self.addAll(item);
}, this);
},
addAll: function(item) {
$('#red').append(item.get('title'));
}
});
blueview = new BlueView;
redview = new RedView;
Upvotes: 0
Views: 100
Reputation: 569
As I remember a json property has to be inside "". Modify the json like this:
[
{"id": 1, "title": "red 1 - "},
{"id": 2, "title": "red 2 - "},
{"id": 3, "title": "red 3"}
]
Upvotes: 1