1

I have a Backbone Paginator Collection:

    var ExercisesCollection = Backbone.Paginator.requestPager.extend({

        model: ExerciseModel,

        paginator_core: {
            url: "/exercises"
        },

        paginator_ui: {
            firstPage: 1,
            currentPage: 1,
            perPage: 10,
            totalPages: 10
        },

        server_api: {
            "filter": "",
            "categories": "",
            "top": function() { return this.perPage; },
            "skip": function() { return this.currentPage * this.perPage; }
        },

        parse: function (response) {
            this.totalPages = response.meta.totalPages;
            return response.data;
        }

    });

I use it in a Backbone View like so:

var Exercises = Backbone.View.extend({

    initialize: function () {
        this.collection = new ExercisesCollection();
        this.collection
            .on( "reset", this.render, this )
            .on( "change", this.render, this);
        this.collection.goTo( 1 );
    },

    render: function() {
        alert("bah!");
    }
});

By looking at the network activity, I can see that it is sending the request to the server and receiving an appropriate response. However it never calls the render function. The reset and change events do not seem to be working.

Any ideas what I'm doing wrong?

Thanks

user1031947
  • 6,294
  • 16
  • 55
  • 88

1 Answers1

2

I had the same problem in 2016 :)
When you're using the 'server' mode, you need to listen to the 'sync' event, not 'reset'.

// in a view
this.listenTo(this.collection, 'sync', this.renderPage);

From backbone docs (http://backbonejs.org/#Collection-fetch):

When the model data returns from the server, it uses set to (intelligently) merge the fetched models, unless you pass {reset: true}, in which case the collection will be (efficiently) reset.

So it doesn't call reset() by default, and so no 'reset' event.

I have found out about the 'sync' event in this answer: https://stackoverflow.com/a/17053978/1657101

As of backbone 1.0, model.fetch() triggers a 'sync'. That's what you should bind to.

Community
  • 1
  • 1
DarthVanger
  • 1,063
  • 10
  • 10