Backbone.js Can't we have tagName?

I just started with backbone.js, and one thing I noticed is that sometimes I don’t want the tagName contain / encapsulate my view template code. If I leave it in '' or 'span' , in my code I get unnecessary div and span .

An alternative I found is to remove the containing tag from my template ( <div class="photo_box"> in my example, as shown below), and use it as tagName in my view. In most cases, this tag will contain the class ( .photo_box ), and I still need to do addClass to (this.el). I don't like scattering template code.

Is there another way?

Js

 // Views PhotoListView = Backbone.View.extend({ tagName: 'span', render: function() { _.each(this.model.models, function(photo) { $(this.el).append(new PhotoListItemView({ model: photo }).render().el); }, this); return this; } }); PhotoListItemView = Backbone.View.extend({ tagName: 'span', template: _.template($('#tpl-PhotoListItemView').html()), render: function() { $(this.el).html(this.template( this.model.toJSON() )); return this; } }); 

HTML

 <!-- Templates --> <script type="text/template" id="tpl-PhotoListItemView"> <div class="photo_box"> <div class="photo_container"> <img src="img/profiling/<%= photo_id %>.jpg" class='photo' /> </div> </div> </script> 

Result

 <div id="photo_list"> <span> <span> <div class="photo_box"> <div class="photo_container"> <img src="img/profiling/f_001.jpg" class="photo"> </div> </div> </span> <span> <div class="photo_box"> <div class="photo_container"> <img src="img/profiling/f_002.jpg" class="photo"> </div> </div> </span> </span> </div> 
+4
source share
2 answers

You do not need to manually add the class name. You can use the className property:

 PhotoListItemView = Backbone.View.extend({ tagName: 'span', className: 'photo_box', 

Btw, I recommend this HTML structure:

 <ul id="photo_list"> <li> <img src="img/profiling/f_001.jpg" class="photo"> </li> <li> <img src="img/profiling/f_003.jpg" class="photo"> </li> </ul> 
+7
source

You can always use setElement :

setElement view.setElement(element)

If you want to apply the Backbone view to another DOM element, use setElement , which will also create a caching link to $el and move the delegated views of the view from the old element to the new one.

and completely forget about tagName :

 PhotoListItemView = Backbone.View.extend({ template: _.template($('#tpl-PhotoListItemView').html()), render: function() { this.setElement(this.template(this.model.toJSON())); return this; } }); 

Demo: http://jsfiddle.net/ambiguous/XWEMg/


As an aside, <span> is a poor choice for a container (even temporary) due to its limited permitted content ; you risk your browser reordering your HTML to get something valid if you start throwing arbitrary HTML into <span> . A <div> is a much safer choice, since it can contain almost everything.

+22
source

All Articles