Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

calling javascript on rendering views in BackBone js. post-render callback?

Tags:

behold, a backbone view render call:

render: function() {   $(this.el).html(this.template({title: 'test'}));  //#1   this.renderScatterChart();   return this; }, 

so, I call a standard render at #1. and then, i call a method [this time, it is a wrapper for charting lib] that looks for a div. the div is rendered by the render call. but at this point, it is not attached to the DOM yet (right?). so the chart call sadly dies.

what is the pattern for this? i'd love hear that there is a post-render callback. i've tried a few hacks around this, and sometimes i get the chart to work, but events don't bind.

like image 235
whatbird Avatar asked Feb 04 '12 23:02

whatbird


People also ask

How do you render in JavaScript?

The Render Functionrender() function takes two arguments, HTML code and an HTML element. The purpose of the function is to display the specified HTML code inside the specified HTML element.

What are views in Backbone JS?

The Backbone. js Views specify how your data looks like. They represent model's data to the users. They can be used with any JavaScript template library.

What does render JavaScript mean?

Educative Answers Team. Javascript uses the document object model (DOM) to manipulate the DOM elements. Rendering refers to showing the output in the browser. The DOM establishes parent-child relationships, and adjacent sibling relationships, among the various elements in the HTML file.


1 Answers

My usual approach for this sort of thing is to use setTimeout with a timeout of zero to arrange for something to happen once the browser gets control again. Try this:

render: function() {     $(this.el).html(this.template({title: 'test'}));      var _this = this;     setTimeout(function() {         _this.renderScatterChart();     }, 0);      return this; } 

Or, if renderScatterChart is already bound to the appropriate this:

render: function() {     $(this.el).html(this.template({title: 'test'}));     setTimeout(this.renderScatterChart, 0);     return this; } 

You can also use _.defer if you want to be more explicit about what you're up to:

defer _.defer(function, [*arguments])

Defers invoking the function until the current call stack has cleared, similar to using setTimeout with a delay of 0.

So you could also do it like this:

// Assuming that `renderScatterChart` is bound to the appropriate `this`... render: function() {     $(this.el).html(this.template({title: 'test'}));     _(this.renderScatterChart).defer();     return this; }  // or if it isn't bound... render: function() {     $(this.el).html(this.template({title: 'test'}));      var _this = this;     _(function() {         _this.renderScatterChart();     }).defer();      return this; } 
like image 106
mu is too short Avatar answered Jan 27 '23 04:01

mu is too short