Ivan
Ivan

Reputation: 157

Render after adding a new model

I have some models on a server already bootstraped. They are fetching and rendered successfully. But when I'm saving a new model, I cannot get it rendered. When I reaload the page - everything is ok: newly added model rendered. How can I get it rendered on a fly (without refreshing the page)?

Here's my ListView

var GroupView = Backbone.View.extend({
    tagName: 'ul',

    initialize: function () {
        this.collection = new StudentsCollection();
        // this.collection.on('add', this.render, this);
        this.collection.on('update', this.render, this);
        // this.collection.on('reset', this.render, this);
        this.collection.fetch({
            success: function () {
                console.log('success!');
            },
            error: function (collection, response, options) {
                console.log(options);
            }
        });
    },

    render: function () {
        // this.$el.empty();
        var self = this;

        this.collection.each(function (student) {
            var studentView = new StudentView({
                model: student
            });
            self.$el.append(studentView.render().el);
        });
        $('.container').append(this.$el);
    }
});

I tried 'add' event on a collection, but that's just double everything. Any thoughts?

Upvotes: 0

Views: 24

Answers (1)

ivarni
ivarni

Reputation: 17878

Using add on collection is the correct thing to do, since you want to do something when a model is added. The reason you're seeing double of everything (I suspect except the recently added one) is because you're render-function is just appending to the $el.

Backbone is not going to clear out your existing view before rendering, you have to decide what strategy to use.

The simplest solution is to simply add this.$el.empty() and the start of your render. I don't recommend doing this as it will re-render the entire thing each time you add a model.

A better solution is to create a function for adding just one view to the existing view and trigger that on add.

Someting like the below

initialize: function() {
    ...
    this.collection.on('add', this.addStudentView, this);
    ...
}

and

addStudentView: function(model) {
    var studentView = new StudentView({
        model: model
    });
    this.$el.append(studentView.render().el);
}

Upvotes: 1

Related Questions