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;
}
The Backbone. js Views specify how your data looks like. They represent model's data to the users. They can be used with any JavaScript template library. They handle users input events, bind events and methods, render model and collection and interact with users.
It is designed for developing single-page web applications, and for keeping various parts of web applications (e.g. multiple clients and the server) synchronized. Backbone was created by Jeremy Ashkenas, who is also known for CoffeeScript and Underscore. js.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With