Reputation: 193
Long time back I was sort of convinced that render()
is prerogative of view itself and not parent view's concern.
However lately I read about delegateEvents
in backbone and had mixed feeling about how I implemented. So far everywhere I was calling render()
method within initialize
method.
I have not done exhaustive testing or found an use case of where I may face a problem. However it gives me feeling of potential problem lurking with the way I have done.
Could you please share your experience? What are the problems with calling render()
method within initialize
? And how would you do it?
Is parent dictating child where to and when to render itself r is it still within the boundaries of SoC (separation of concern)?
Upvotes: 2
Views: 5872
Reputation: 1446
"...long time back i sort of was convinced myself that render() is prerogative of view itself and not parent views concern."
You were on the right track. While people often treat render
like a public method, you will find that calling render from outside the view will lead to nothing but spaghetti code and chaos.
The best practice is to render (or schedule a render) as part of initialization, and in response to the appropriate events on the relevant models.
Upvotes: 1
Reputation: 18556
Basically I see about 3 different scenarios for rendering the first 2 are a the render-within parent,
// parent view's render
render: function() {
var child = new ChildView({el: this.$('.foo'), model: bar, ...});
this.$el.append(child.render().el);
}
which is basically the case where the parent dictates where or when the child is rendered, and the render-within-itself,
// parent view's render
render: function() {
var child = new ChildView({el: this.$('.foo'), model: bar, ...});
this.$el.append(child.el);
}
// child view's initialize
initialize: function() {
...
this.render();
}
which is the case where the child view dictates when the rendering is done. My opinion is that the latter is better. Your application should be arranged so that only the view itself knows when it should be rendered (should it be right after initialization or fetching a model/collection). I do not see ANY problems in calling render
within initialize
, even though delegateEvents
is called after it. Populating el
shouldn't make any difference with how it functions.
Calling render
within initialize
is a good practice, because it works regardless of the situation and unifies the way you do render (you'll adding views that render after fetch the same way as other views). I haven't run into any problems doing rendering this way yet and apparently you haven't either!
Hope this helps (or helps to reassure you)!
Upvotes: 1