Search code examples
javascriptbackbone.jsunderscore.js

How to display only 3 items from my backbone collection


Im new in backbone and Im stuck with this issue. I need to display 3 items for my collection and the after clicking show more display another 3 of them. I know I can use for example first() method for underscore.js but how ? Here is my code:

$(function() {
var Tasks = Backbone.Model.extend();
var TasksList = Backbone.Collection.extend({
    model: Tasks,
    url: 'json/data.json'
}); 


var TasksView = Backbone.View.extend({
    el: "#tasks",
    template: _.template($('#taskTemplate').html()),
    render: function() {
        _.each(this.model.models, function(tasks){
            var taskTemplate = this.template(tasks.toJSON());
            $(this.el).append(taskTemplate);
        }, this);

        return this;
    }
});

var tasks = new TasksList();    
var tasksView = new TasksView({model: tasks});
tasks.fetch({reset:true});
tasks.bind('reset', function () {
    tasksView.render();
    });    
});

Solution

  • You can use underscores first method. Hope this helps

    var TasksView = Backbone.View.extend({
    
        el: '#tasks',
    
        template: _.template($('#taskTemplate').html()),
    
        initialize: function () {
            this.listenTo(this.collection, 'reset', this.render);
        },
    
        render: function () {
            _.each(this.collection.first(3), function (task) {
                var html = this.template(task.toJSON());
    
                this.$el.append(html);
            }, this);
    
            return this;
        }
    }
    
    var tasks = new TasksList(),   
        tasksView = new TasksView({ collection: tasks });
    
    tasks.fetch({ reset:true });