2
votes

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?

1
The more common pattern would be to render the child view(s) from within the parent render function. Seems like you're asking for an anti-pattern.Stephen Thomas
I may be asking for an anti-pattern, dunno yetAlexander Mills
I think we can imagine a simple scenario where you render a bunch of childviews, but move them to a new parent view, and want to avoid re-rendering the childviews.Alexander Mills
Views are rendered into DOM nodes, those nodes don't have to be on the page (unless they contain, say, Google maps or other things that care about the size and position of things). Views are generally light weight so trying to reuse them is more trouble than it is worth, just destroy and recreate them as needed.mu is too short

1 Answers

1
votes

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>