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:
url
property, but I don't really have a URL in mind - I was planning to bind data via Ajax. url
property 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
.
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:
url
property, but I don't really have a URL in mind - I was planning to bind data via Ajax. url
property 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
var ajaxData = [{ 'breed' : 'persian' }]; // Backbone.Collection expects an array
var catCollection = new CatCollection(ajaxData);
// catCollection.fetch(); fetch will try to update the data from the server
or use the built-in url/parse to build your models
var CatCollection = Backbone.Collection.extend({
model: Cat,
url: "your ajax source",
parse: function (csv) {
//convert your csv in an array of objects
return csvtoarray;
},
fetch: function (options) {
options = options || {};
options.dataType = "text";
return Backbone.Collection.prototype.fetch.call(this, options);
}
});
var catCollection = new CatCollection();
catCollection.fetch();
Converting your data server-side to JSON will probably be easier than trying to write a CSV parser in JS.