Search code examples
jsonbackbone.js

Backbone.js collection fetching with JSON


I'm using Backbone.js and Phil Sturgeon's CI rest server (AMAZING TOOL, definitely recommended).

Here is my page: http://interr0bang.net/7357/fetch/. It is very basic, a model (Event), a collection (Events), and a view (EventView). The collection is located at http://api.interr0bang.net/calendar/events and returns a JSON array that has been validated using jsonformatter.curiousconcept.com.

Here's the code:

$(function(){
    var Event = Backbone.Model.extend();
    var Events = Backbone.Collection.extend({
        model: Event,
        url: 'http://api.interr0bang.net/calendar/events',

    });
    var EventView = Backbone.View.extend({
        initialize: function(){
            _.bindAll(this, "render","count");
            this.collection = new Events();
            this.collection.bind("change",this.count);
            this.collection.fetch();
            this.counter = this.collection.length;
            this.render();
        },
        render: function(){
            this.el.html(this.counter);
        },
        count: function(){
            this.counter = this.collection.length;
        }
    });
    eventView = new EventView({el:$('#collection')});
});

The view renders fine, but it always displays 0, and Firebug shows the GET request, and the status is 200 OK, but the response body is empty... Why doesn't this work?


Solution

  • You have a configuration problem. If you look at your browser, it reports:

    XMLHttpRequest cannot load http://api.interr0bang.net/calendar/events. Origin     
    http://interr0bang.net is not allowed by Access-Control-Allow-Origin.