Reputation: 16726
I find the usage of the different elements of backbonejs quite ambiguous. From my undestanding, this was the intention as backbone didn't want to be a framework, but more of a set of tools/objects.
I understand most parts of backbonejs, but i'm still questioning what is the correct usage for a view's initialize() and render() calls. In other words, what logic should be placed within each.
Could someone explain what is best practice or what is considered correct usage of these calls within a view?
Upvotes: 0
Views: 199
Reputation: 7225
This is a pretty far-ranging question, but I'll give it a try. The key takeway here is that there is no such thing as "the correct usage" for these calls. Backbone is flexible on purpose and meant to adapt to your needs. That's why it still has its place in a world of more sophisticated, but "opinionated" frameworks (which tell you that it's "my way or the highway").
Backbone does not use any magic with respect to rendering. The render()
method is a no-op and not even invoked automatically for you. Its existence is nothing more than a hint how things are usually done.
The initialize()
method, however, is invoked automatically when the view is instantiated. Backbone guarantees that at that point, the top-level DOM element of the view (the el
) has already been created and is ready to have stuff attached to it.
But again, that's pretty minimal: the top-level element is there, but not yet attached to the DOM (unless you passed options.el
to the constructor, setting the el
to an existing element). Inserting the el
into the DOM is your job, too.
So you are free to decide how to wire things up. What I typically do is this:
Most of my views have a template, which is commonly assigned to the template
property of the view. (Again, just a convention, no magic involved. You could name it foo
.) That template is compiled in initialize()
.
In initialize()
, I set up the relationship with a model or a collection which the view is supposed to represent. Ie, the view observes model/collection events and is made to call render
when the data has changed. (You don't have to use a Backbone entity as your data source, of course ... could be anything).
In render()
, the data is fed into the template, and the result becomes the innerHTML of the el
. Afterwards, I make sure the el
is inserted into the DOM if it isn't already.
The first call to render()
should happen when the data is ready. The right moment depends on the app. Perhaps render()
is the last call in initialize()
, or some event will kick it off later on.
If a lot of that sounds like repetitive boilerplate to you, yes, that's exactly what it is. Frameworks like Marionette exist on top of Backbone to take care of that.
But there is a sigificant performance penalty for that framework magic. So when I have to generate a lot of views, I stick to the generic Backbone stuff (and use one of my own components for speeding up the template handling.)
Upvotes: 1