3
votes

I’m using Backbone.js and I’d like to extend it with Marionette.js. One thing, that works in Backbone, but I couldn’t make it with Marionette views, is the way I handle pagination. In Backbone I have a method called pagination just inside the Backbone.Collection that looks like this:

var ordersCollection = Backbone.Collection.extend({
        url: 'collection',
        model: Order,
        pagination: function(page) {
            perPage = 10;
            var collection = this;
            collection = _(collection.rest(perPage * page));
            collection = _(collection.first(perPage));
            return collection;
        }
    });

Then I can create paginated collection just like this:

ordersCollection = new OrdersCollection();
ordersCollection.fetch();
ordersFirstPage = ordersCollection.pagination(1);

But when I try to pass this collection to Marionette.CompositeView, I get this error

Uncaught TypeError: Object [object Object] has no method 'on'

I know that it’s because of my pagination function doesn’t return collection in the exact Backbone.Collection format. So I tried to fix it using:

ordersFirstPage = new Backbone.Collection(ordersFirstPage)

The TypeError disappeared, but then the values passed by CompositeView to its template behaved as empty.

Any ideas, how to modify either the collection object or the pagination function to get it working?

2

2 Answers

0
votes

You should not build a Backbone.Collection but a 'ordersCollection'. E.g:

ordersFistPage = new OrdersCollection(ordersCollection.pagination(1));

And you should check if the values you want to access is in the CompositeView(the collection should have the data, you can set the proprieties of the collection) or the ItemView of the CompositeView (the models from your collection should have the data).

0
votes

Finally I've managed it by using _.flatten() in pagination function. So I used flatten on the result of _.first() method used in collection.

My pagination collection now look like this:

var ordersCollection = Backbone.Collection.extend({
        url: 'collection',
        model: Order,
        pagination: function(page) {
            perPage = 10;
            var collection = this;
            collection = _(collection.rest(perPage * page));
            collection = _(collection.first(perPage));
            collection = _(collection).flatten(true);
            return collection;
        }
    });

And it seems to be the most simple and elegant solution for pagination of Backbone/Marionette collections.