Search code examples
javascriptbackbone.jsfetchbackbone.js-collections

Backbone uncaught error:


In my chrome console it says there is an error from Backbone - Uncaught Error: A "url" property or function must be specified

I was able to fix the problem by replacing my Backbone.js script from version 1.1.2 to 1.0.0. Can anyone explain why the newest version of Backbone is giving me an error where as the older version doesn't?

Is there something wrong in my syntax below where I'm trying to set the collection url to an api address?

    var daysCollection = new DaysCollection([], {
        url: 'http://api.wunderground.com/api/94c558eeb4e503dc/forecast/q/CA/San_Francisco.json'
    });

    daysCollection.fetch({
        success: function (collection, response, options) {
            console.log(collection, response);
        },
        error: function (collection, response, options) {
            console.log('error');
        }
    });

Let me know if I need to provide more details.


Solution

  • Backbone doesn't add the url or urlRoot from the options, to models or collections. From the changelog for 1.1.0:

    Backbone Views no longer automatically attach options passed to the constructor as this.options and Backbone Models no longer attach url and urlRoot options, but you can do it yourself if you prefer.

    Although it doesn't specific say Collections , if you look at the code diff between (1.0.0 and 1.1.2) you will see that the following line has been removed from the Backbone.Collection constructor:

    if (options.url) this.url = options.url;
    

    There are a couple of solutions, the first is to just set the url afterwards:

     var daysCollection = new DaysCollection([], {});
     daysCollection.url = 'http://api.wunderground.com/api/94c558eeb4e503dc/forecast/q/CA/San_Francisco.json';
    

    Or, you could add that options line to your initialize function for the collection:

    var DaysCollection = Backbone.Collection.extend({
        initialize: function(models, options){
             if (options.url) this.url = options.url;
        }
    });