Chris Dutrow
Chris Dutrow

Reputation: 50362

Backbone or Marionette callback for when a Collection item displays on the page?

Question

What is a good way to run some code only after a Backbone or Marionette Collection item has displayed onto the page?

More info

The reason I need to do this is because I am using google charts. The charts do not render quite right unless they are actually visible on the page when they are being rendered (ie: not hidden explanation). It appears that when the collection item's onRender function is called, the view is not quite rendered completely on the page.

The "fix" I'm currently is to use setTimeout to render the charge a half second after onRender is called. This works, but is an ugly hack:

Backbone.Marionette.ItemView.extend({
   ...
   onRender: function(){
      var chart = ...;
      var chart_data = ...;
      var options    = ...;
      setTimeout(function(){
            chart.draw(chart_data, options)  
         },
         500
      );
   }
   ...
})

I've read in other places that onShow works, but if I understand correctly, this method only is called when working Marionette regions.

Upvotes: 3

Views: 90

Answers (2)

maxlath
maxlath

Reputation: 1841

otherwise, you can use a plugin like jquery.inview to get a inview event once a given element becomes visible:

Backbone.Marionette.ItemView.extend({
   events:{
     'inview #chartContainer': 'renderChart'
   },
   renderChart: function(){
      var chart = ...;
      var chart_data = ...;
      var options    = ...;
      chart.draw(chart_data, options)
   },
   ...
})

Upvotes: 1

nicoespeon
nicoespeon

Reputation: 369

Unfortunately, Marionette's onRender method doesn't mean that the object is actually added to the DOM.

If you were using Marionette's regions, then onShow would probably do the job because of the timing. But as it can be detached from the DOM there is no guarantee that views are actually displayed.

The actual clean solution is to use the onAttach event added to Marionette v2.3. Hope this will solve your problem — but I'm confident with that =)

Upvotes: 3

Related Questions