user2054833
user2054833

Reputation: 2165

Updating backbone view when collection change

When the first page of my Backbone app load I fetch a collection then iterate over it to render the page:

Page Router:

    home: function ()
    {
        new BodyView ({page:'home'});

        new HomeView();
        new PostView();

        postCollection = new PostCol({userId:getId(),start:0,offset:50});
        postCollection.fetch();
        postView = new Post({collection:postCollection});

    },

Post View:

    el:'.stream',
    initialize: function ()
    {
        this.collection.on('reset',this.render.bind(this));
        this.collection.on ('change',this.render.bind (this));
    },
    render: function ()
    {
        this.collection.each (function (model)
        {
            actor = new Actor ({model:model});
            this.$el.append (actor.render().el);
        },this);
        return this;
    },

What I am trying to accomplish now is that when a user save some data in another view it update the Post view. This is what I did but its not working.

Other View:

     post = new PostModel ({userid:getId(),post:postText,objectid:0});
            post.save({},
            {
                success: function (response)
                {
                    postCol = new PostCol ({userId:getId(),start:0,offset:50});
                    postView = new Post ({collection:postCol});
                    postCol.fetch ().success({change:true});
                },
                error: function (response)
                {
                    console.log (response);
                }
            }
            );

Upvotes: 1

Views: 6598

Answers (1)

Paul Hoenecke
Paul Hoenecke

Reputation: 5060

It looks like you postCollection is global, so you could update the existing model instead of creating a new one.

// find existing model in the collection.
var post = postCollection.get(getId());
// save model with updated info.
    post.save({post:postText},
    {
        success: function (response)
        {
            // if the save succeeded, the Post view will re-render,
            // since you are listening for the 'change' event.
            // so here, you don't really need to do anything.
        },
        error: function (response)
        {
            console.log (response);
        }

    );

Instead of this.collection.on ('change',this.render.bind (this)); in the Post view, you could do this in the individual Actor view, so the whole collection does not re-render.

this.model.on ('change',this.render, this); // 'this' as third parameter replaces the `bind`

Upvotes: 1

Related Questions