The appropriate way to call render () in BackboneJS

In most of the BackboneJS examples I've seen, parent views call the render() function on child views. It seems a little strange to me. Maybe this is completely for optimization or something else, but I do not understand why the optimization could not happen in the very representation of the child. Shouldn't a child be responsible for calling his own render() ? It seems that in all my views I am getting something like:

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

In addition, if the parent view updates the child representation of the model , how should the child know that the model has changed (and therefore need to call render() )? I assume that in this case the parent is forced to call the render() child. Although this is somewhat deduced, why should a parent know that a child needs to be re-rendered when changing its model? It seems that the call to the rendering function of the child view is outside the domain of the parent view.

+7
source share
1 answer

Like everything related to Backbone, this is a rather subjective question. But here are a few reasons you might want to give it to your parents:

  • It is perfectly reasonable to think that the parent view may need to make sure that the child views are displayed before the rest of the rendering. For example, a parent may require the size of a container element based on the size of its children or show the container only after its contents are displayed by child views.

  • The initialization rendering template only works if you don’t need to do other things at first - for example, one common template for attaching the view to the change model event, calling this.model.fetch() and rendering in the callback. In this case, especially if you care about the execution order of the different renders, it’s nice to have one event listener for the parent, and then have a parent transaction with rendering for the children, instead of having bindings to each child, although these children won’t cause fetch() .

  • In addition, if parental rendering does not allow children to reverse themselves, for example, in response to more specific events. Having a parent call to child.render() just helps make sure that this happens by the time the parent has finished rendering.

It's also worth noting that views have a default no-op for render . Thus, the parent can call render() for the child, not being sure that he will do something.

In response to the question: β€œWhat if a parent changes a child model?”, One option is to not do this β€” always create a new child for each new model. But this may not match your architecture - in this case, having a parent responsible for re-rendering makes sense.

+13
source

All Articles