Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Appropriate way to call render() in BackboneJS

In most BackboneJS examples I've seen, parent views call the render() function on child views. This seems a little odd to me. Maybe it's completely for optimization or something, but I don't see why the optimization couldn't take place within the child view itself. Shouldn't the child view be responsible for calling its own render()? It seems like in all my views I end up with something like:

initialize: function() {
    this.render();
}

Also, if my parent view updates the child view's model property, how is the child supposed to know that the model changed (and therefore render() needs to be called)? I assume in this case the parent is forced to call the child's render(). Although it's somewhat inferred, why should the parent need to know that the child needs to re-render when its model is changed? It seems like calling the render function of the child view is outside of the parent view's domain.

like image 647
Aaronius Avatar asked Oct 11 '11 20:10

Aaronius


1 Answers

Like pretty much everything Backbone-related, this is a pretty subjective question. But here are a few reasons you might want the parents to render:

  • It's perfectly reasonable to think that the parent view might need to make sure that the child views are rendered before the rest of the rendering takes place. For example, the parent might need to size a container element based on the size of its children, or show a container only once its contents are rendered by the child views.

  • Your "render on initialize" pattern only works if you don't need to do other things first - for example, one common pattern is for the view to bind to the model's change event, call this.model.fetch(), and render in the callback. In this case, especially if you care about execution order of the different renders, it's nice to have a single event listener on the parent and then have the parent deal with rendering children, rather than having bindings with every child, even though those children won't be calling fetch().

  • Also, having the parent render the children doesn't preclude the children re-rendering themselves, e.g. in response to more specific events. Having the parent call child.render() just helps to ensure that this has happened by the time the parent is finished rendering.

It's also worth noting that views have a default no-op for render. So the parent can call render() on the child without having to be sure it'll do anything.

In answer to "what if the parent changes the child's model?", one option is, don't do that - always create a new child for each new model. But that might not fit your architecture - in which case having the parent responsible for re-rendering the child makes perfect sense.

like image 95
nrabinowitz Avatar answered Nov 03 '22 09:11

nrabinowitz