1

I am trying to make ajax request to server. I am using fetch() method on collection. It successfully retrieves data from server after monitoring google chrome network tab.

Here is scenario.

I have Model below

var Model = Backbone.Model.extend({
    urlRoot: '/contacts',
});

collection below

var Collection = Backbone.Collection.extend({
    model: Model,
    url: '/contacts'
});

ViewOne below

var ViewOne = Backbone.View.extend({
    initialize: function () {
        var collection = new Collection().fetch(); // also tried with these options { wait:true, reset: true, async: false }
        new ViewTwo({ collection: collection });
    }
});

Below is ViewTwo

var ViewTwo = Backbone.View.extend({
    initialize: function () {
        this.collection.each(this.render, this); // Uncaught TypeError: undefined is not a function
    },

    render: function () {
        console.log(this.model);
    }
});

As you can see I am getting Uncaught TypeError: undefined is not a function error.

this.render exist so that is not a problem. The problem is each function on this.collection. How can I solve this proble?

2 Answers2

2

simply create new view in success callback of fetch

var ViewOne = Backbone.View.extend({
    initialize: function () {
        var collection = new Collection();
        collection.fetch({
         success:function(){ 
            new ViewTwo({ collection: collection });
            }
             }); 
    }
});
StateLess
  • 5,344
  • 3
  • 20
  • 29
1

Backbone API is not fluent, which means that Collection.fetch does not return itself, it returns the Ajax object used in fetch.

Try

var ViewOne = Backbone.View.extend({
    initialize: function () {
        var collection = new Collection();
        collection.fetch();

        new ViewTwo({ collection: collection });
    }
});

And note that the collection.fetch is asynchronous, this.collection will be probably empty in ViewTwo.initialize. See Backbone.js - data not being populated in collection even though fetch is successful for example.

Community
  • 1
  • 1
nikoshr
  • 32,926
  • 33
  • 91
  • 105