I’ve just started using Backbone.js. I want to create a Collection and add some data from an external source.
The data is actually currently in CSV, not JSON, but I could re-render it in JSON if that is going to be a lot easier.
So, two questions:
- Where do I bind external data to the Collection? It complains if I don’t specify a
urlproperty, but I don’t really have a URL in mind – I was planning to bind data via Ajax. - Should I re-render my data in JSON, rather than CSV, and use the Collection’s
urlproperty to load it?
I just tried loading data directly into the Collection, rather than via the url property:
var Cat = Backbone.Model.extend({});
var CatCollection = Backbone.Collection.extend({
model: Cat
});
var ajaxData = { 'breed' : 'persian' } // simple example of external data
var catCollection = new CatCollection(ajaxData);
catCollection.fetch();
But this gives an error: Uncaught Error: A "url" property or function must be specified.
Either initialize/reset your collection with an array created elsewhere without using the fetch method for your collection
or use the built-in url/parse to build your models
Converting your data server-side to JSON will probably be easier than trying to write a CSV parser in JS.