Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Backbone.js: bind data to Collection using Ajax?

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:

  1. Where do I bind external data to the Collection? It complains if I don't specify a url property, but I don't really have a URL in mind - I was planning to bind data via Ajax.
  2. Should I re-render my data in JSON, rather than CSV, and use the Collection's 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.

like image 529
Richard Avatar asked Aug 07 '26 14:08

Richard


1 Answers

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.

like image 95
nikoshr Avatar answered Aug 10 '26 13:08

nikoshr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!