crawf
crawf

Reputation: 9658

Backbone.js updating models in-place from server

Here's the scenario - a page renders a collection of widgets that display some aggregated data to the user. This data is retrieved from an API, and is regularly re-calculated. Displaying these are fine (thanks to the fine folks at stackoverflow), but I'm just having trouble re-rendering the views when data is changed on the server.

Notably, I would prefer the more efficient approach of not re-rendering all the pages' widgets (could be 10+) if only one has updated data. Fetching a collection at an interval is easy enough, but what are the best practices regarding rendering a chaned model? I've seen various posts about overwriting the sync function, but not really sure where to go.

Is there any way we can re-render the view(s) in-place (rather than re-appending to the page).

Thanks so much

Upvotes: 1

Views: 3070

Answers (2)

nikoshr
nikoshr

Reputation: 33344

You can bind to specific changes on the model/collection to trigger the render methods of the widgets. For example, on a model:

var Widget1=Backbone.View.extend({
    initialize: function() {
        // all changes on the model will render the widget
        this.model.on("change", this.render, this); 
    },

    render: function() {
        console.log("Render W1");
        this.$el.html("W1 :"+this.model.get("name")+" "+this.model.get("detail"));
        return this;
    }
});
var Widget2=Backbone.View.extend({
    initialize: function() {
        // only a change on `detail` will render the widget
        this.model.on("change:detail", this.render, this);  
    },

    render: function() {
        console.log("Render W2");
        this.$el.html("W2 :"+this.model.get("detail"));
        return this;       
    }
});

A more complete Fiddle to play with http://jsfiddle.net/GqnKC/

Upvotes: 1

fguillen
fguillen

Reputation: 38792

I think what you need is update the existing Models into the Collection without refresh the whole Collection. Check my answer here.

Upvotes: 2

Related Questions