Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoid re-rendering images and other stuff from backbone views

when I rerender a backbone view, what is a good way to skip re-rendering things like images and google maps? My photo and map views tend to flicker really bad every time the view is re-rendered (which is quite often). With the images especially, it is the case that the templating engine is laying out the layout from scratch, which causes the image tags to fetch the bitmap either from the server or from the cache once again.

Of course, I still want the view to remain kind of agnostic of the layout, so technically it shouldn't know that we are going to display an image, right?

like image 745
Preslav Rachev Avatar asked Jun 13 '12 08:06

Preslav Rachev


2 Answers

I'm gonna offer a solution that is in conflict with your assumption "the View should be agnostic of the template".

If you call render() any time anything has changed in the Model you will have this blinking in your browser, especially if the template is big.

My recommendation is separate the render of the View which happens only once when the View is first time visualized and several update helper methods which are in charge of updating small pieces of the View linked to concrete Model attributes.

For example:

// code simplified and not tested
var MyView = Backbone.View.extend({
  initialize: function(){
    this.model.on( "change:title", this.updateTitle, this );
    this.model.on( "change:description", this.updateDescription, this );
    // ... more change:XXX
  },

  render: function(){
    this.$el.html( this.template( this.model.toJSON() ) );
  },

  updateTitle: function(){
    this.$el.find( ".title" ).html( this.model.get( "title" ) );
  },

  updateDescription: function(){
    this.$el.find( ".description" ).html( this.model.get( "description" ) );
  },

  // ... more updateXXX()
})
like image 90
fguillen Avatar answered Sep 28 '22 09:09

fguillen


To get the best result you really don't want to re-render the HTML that contains your media so I would recommend using more targetted views for the content that changes so you don't need to re-render the views with content that doesn't.

like image 22
lecstor Avatar answered Sep 28 '22 08:09

lecstor