Reputation: 63405
I find in several backbone examples different ways to do the same thing
I'd just like to know if any of them is better, and in case they're exactly the same which is the more accepted style
$('#header').html(new HeaderView().render());
vs
new HeaderView({el:$('#header')).render();
and
this.$el.html( this.template() );
vs
$(this.el).html( this.template() );
and finnally
render: function() {
[...]
return this.el;
}
vs
render: function() {
[...]
return this;
}
Upvotes: 5
Views: 1557
Reputation: 38772
el
in the constructorI think always that is possible is better to send el
in the constructor, this way the JS logic will be more decoupled from the DOM structure and not any DOM element name is hard-coded into the JS code.
This is also better for testing proposes so you don't need to recreate the production DOM structure in your tests and you can create a dummy DOM structure and instantiate your Views making reference to any DOM element in your dummy DOM structure.
Also the View becomes more reusable.
this.$el
I think in a performance point of view is better to use:
this.$el
VS
$(this.el)
Due the first option is already precompiled. jQuery consume resources transforming a simple DOM element in a jQuery DOM element and if you use this.$el
this is done only once.
render()
As @muistooshort has said, the standard is to return this
. Normally when you call render()
what you only need from outside is el
so returning el
has a lot of logic but people has agreed to returning this
.
In some way it has its logic due this expression looks awkward:
$('#header').html(new HeaderView().render())
But this other looks very much intuitive and self explained:
$('#header').html(new HeaderView().render().el)
Upvotes: 5