Update a model attribute without rendering the view

by nikoshr

HTML

<script src="http://documentcloud.github.com/underscore/underscore-min.js"></script>
<script src="http://documentcloud.github.com/backbone/backbone-min.js"></script>
<script type='text/template' id='list'>
<ul>
  <% _(children).each(function(model) { %>
    <li>
        <span class='model-<%= model.cid %>-name'><%= model.name %></span> : 
        <span class='model-<%= model.cid %>-name'><%= model.name %></span>
    </li>
  <% }); %>
</ul>
</script>

<p><label>First node name : <input type='text' /></label></p>
<hr />

JavaScript

var source   = $("#list").html();
var template = _.template(source);

var V = Backbone.View.extend({

    initialize: function () {
        this.collection.on('change', this.autoupdate, this);
    },

    autoupdate: function (model) {
        var _this = this,
            changes = model.changedAttributes(),
            attrs = _.keys(changes);

        _.each(attrs, function (attr) {
            _this.$('.model-' + model.cid + '-' + attr).html(model.get(attr));
        });
    },

    render: function () {
        var data, html;

        data = this.collection.map(function (model) {
            return _.extend(model.toJSON(), {cid: model.cid});
        });

        html = template({children: data});

        this.$el.html(html);

        return this;
    }

});

var c = new Backbone.Collection([
    {id: 1, name: "First node"},
    {id: 2, name: "Second node"},
    {id: 3, name: "Third node"}
]);

var v1 = new V({
    collection: c
});
var v2 = new V({
    collection: c
});

$('body').append(v1.render().el);
$('body').append(v2.render().el);

$('input').on('keyup', function (e) {
    c.at(0).set('name', $(e.target).val());
});