Ron
Ron

Reputation: 23466

Backbone.js - Collection request event not firing

I have the following challenge:

I want to implement a loading flower every time I fetch data.

My bootstrapping code looks like this:

var myCollection = new MyCollection({});
myCollection.fetch({
        success: function () {
            var listView = new ListView({model: myCollection});
        }
});

My view looks like this:

var ListView = Backbone.View.extend({
    ...

    initialize: function () {
        this.model.bind('request', this.ajaxStart, this);
        this.model.bind('sync', this.ajaxComplete, this);
        self.render();
    },
});

My problem: The request event is not fired because at the time, the request starts, the ListView is not set up yet.

I tried to change my bootstrapping code but nothing works so far. It's always a chicken or the egg problem. Either I have the view set up at the right place or I have the data.

I tried to pass the collection instance to the view but this seems to be not possible via a set() or another method.

Upvotes: 0

Views: 337

Answers (1)

Alex.Me
Alex.Me

Reputation: 616

You probably should reorganize your structure, setting collection as a view model is not very obvious. Maybe you should add ListModel, that will handle your collection instantiating and updating, and then set your view to listen to your ListModel custom events. As for the chicken / egg problem

var myCollection = new MyCollection();
var myView = new MyView({
  collection: myCollection,
});

myCollection.fetch();

// inside your view
initialize: function() {
  this.listenTo(this.collection, 'sync', this.render);
}

Upvotes: 1

Related Questions