dennismonsewicz
dennismonsewicz

Reputation: 25542

Backbone.js Collection Size - Don't display if limit reached

I have the following code in my Backbone Collection

    loadMore: function() {
        this.offset += 1;
        this.fetch({
            data: {
                limit: 50,
                skip: this.offset
            },
            remove: false,
            success: function(collection) {
                var collectionSize = collection.length;

                console.log(collectionSize);

                if (collectionSize < this.sizeLimit) {
                    this.add(collection);
                } else {
                    eventer.trigger('products:end');
                }
            }.bind(this)
        });
    }

The this.sizeLimit is hard coded (for testing) to 150, but products continue to be added to the collection even though the collectionSize will grow greater than the limit.

Upvotes: 2

Views: 359

Answers (2)

iSchluff
iSchluff

Reputation: 465

Like ivarni said Backbone will automatically add all the models to the collection after parsing. But if you overwrite the parse method you are able to throw out the unnecessary items inbefore:

parse: function(data){
  return data.slice(0, this.sizeLimit);
}

Upvotes: 2

ivarni
ivarni

Reputation: 17878

That's because fetch automatically adds the result to your collection before it even runs your success callback.

See https://github.com/jashkenas/backbone/blob/master/backbone.js#L1002

fetch: function(options) {
  options = _.extend({parse: true}, options);
  var success = options.success;
  var collection = this;
  options.success = function(resp) {
    var method = options.reset ? 'reset' : 'set';
    collection[method](resp, options);
    if (success) success.call(options.context, collection, resp, options);
    collection.trigger('sync', collection, resp, options);
  };
  wrapError(this, options);
  return this.sync('read', this, options);
},

It saves a reference to the success callback you send in, but then runs its own success callback which does a collection.set (or reset if that option was passed in) with the server results before it invokes the one you passed in.

You could start your success callback with emptying the collection and then add as many models as you want but that would generate a lot of unnessescary events. Depending on why you want to have this limit you might be better off either doing the AJAX request yourself without using Backbone's Sync or implementing the limit elsewhere, for example when rendering.

Upvotes: 2

Related Questions