Alexander Mills
Alexander Mills

Reputation: 99970

Backbone.js parent vs. child views

Using Backbone.js for front-end development, is there a reliable way to render a child view before rendering its respective parent view? Is there a pattern for this? I am able to render child views but I have to be careful to always render the parent first. Is there a pattern for safely rendering children before parents?

Upvotes: 2

Views: 471

Answers (1)

Alexander Mills
Alexander Mills

Reputation: 99970

There is one way to do this, using jQuery. jQuery has a find() function. https://api.jquery.com/find/

say I have a Backbone.View instance that creates and writes to its self-defined element (el) which is a div element by default. The code below is inside the render function of my view:

              var self = this;

              var ret = EJS.render($template, {});  //get the template html

              self.$el.html(ret);  //put the html string into self.$el (still not in the DOM though!!)

              //Facebook's React.js lib
              React.render(
                  <TimerExample start={Date.now()} />,
                   $(self.el).find('#react-timer-example-div-id')[0]
               );


              React.render(
                  <MenuExample items={ ['Home', 'Services', 'About', 'Contact us'] } />,
                  $(self.el).find('#react-menu-example-div-id')[0]
               );


             //using the two-way data binding lib "Rivets"
             Rivets.bind( $(self.el).find('#some-id')[0], {obj: exampleObj})

The above works, and I would say it's a great solution to render child views to a parent view, without the parent view first being in the DOM. The trick, as I said, is to use $(this.el).find('#xyz');. If there is a better way, I'd love to hear it, but this seems to work quite well.

My template for the above represented by $template, looks like this:

<div>
    <div id="react-timer-example-div-id">timer example goes here</div>
    <div id="react-menu-example-div-id">menu example goes here</div>
    <div id="some-id">blah blah</div>
</div>

Upvotes: 1

Related Questions