Backbone JS: View signatures to prevent repaints

by on

A nice thing about backbone is being able to bind a view render to new data. But sometimes you get new data, but it's not actually new, it's the same data that has not been updated. This will still cause the view to repaint because the event will fire.

To combat this, I've started putting signatures on my views.

In the initializer for the view:

this.signature = "";

Then in the render method, I do a reduction on the data that drives the view and compare signatures and decide to paint or not:


// Create a signature from the "Posts" that this view renders
var new_signature = _.reduce(posts, function(memo, post) {
// Store the id and number of comments. This represents what a
// "changed" post is for the view
memo.push([post.get('id'), post.get('num_comments')].join(','));
return memo;
}, []).join('|'); // joined with pipes for each post

// If the signature is the same, end the render
if (new_signature === this.signature) {
this.signature = new_signature;
return;
}
// Otherwise store the signature
this.signature = new_signature;
// Your view code down here

This is essentially caching with a custom cache key. Except instead of retrieving a cached value, we leave the dom as-is. This cuts down on repaint "flickering".

blog comments powered by Disqus