Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Backbone style: how to deal with the el element of a view

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;
}
like image 220
opensas Avatar asked Aug 05 '12 05:08

opensas


People also ask

What is a backbone view?

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.

What is Backbone used for?

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.


1 Answers

Send, or not to send, el in the constructor

I 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.

Using 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.

What to return in 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)
like image 125
fguillen Avatar answered Sep 21 '22 15:09

fguillen