Load more data button backbone

2019-09-17 19:38发布

I have a problem I was trying to write a simple app which will load more data for json file after clicking show more button but cant figure it out how to do this :/ I have app which show 3 elements from json file and I want to display 3 more after click show more button. I have 9 items in json and after reach the limit (this 9 items) and click show more I want to display alert that the limit is reached. The 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',
    con: 3,
    events: {
        'click #load-more': 'load_more'
    },

    template: _.template($('#taskTemplate').html()),

    initialize: function () {
        this.listenTo(this.collection, 'reset', this.render);

    },

    render: function () {
        _.each(this.collection.first(this.con), function (task) {
            var html = this.template(task.toJSON());

            this.$el.append(html);
        }, this);

        return this;
    },
    load_more: function (){
        //loade more scope
    }
});

var tasks = new TasksList(),   
    tasksView = new TasksView({ collection: tasks });

tasks.fetch({ reset:true });

1条回答
Anthone
2楼-- · 2019-09-17 20:38

Move your class definitions outside DOM ready function, its bad practice

renderTask: function (task) {
    var html;

    html = this.template(task.toJSON());

    this.$el.append(html);
},

render: function () {
    var tasks = this.collection.first(this.con);

    _.each(tasks, this.renderTask, this);

    this.count = tasks.length;
},

onClickMore: function (event) {
    var tasks = this.collection.models.slice(this.count, this.count + this.con);

    event.preventDefault();

    if (tasks.length) {
        _.each(tasks, this.renderTask, this);

        this.count += tasks.length;
    } else {
        alert('Limit is reached');
    }
}
查看更多
登录 后发表回答