Alex Rivera | Logout

Setting id and className dynamically in Backbone.js views

Asked 2011-08-11T21:32:26.397
85

I am in process of learning and using Backbone.js.

I have an Item model and a corresponding Item view. Each model instance has item_class and item_id attributes, that I want to be reflected in as the 'id' and 'class' attributes of the corresponding view. What's the correct way to achieve this ?

Example:

var ItemModel = Backbone.Model.extend({      
});

var item1 = new ItemModel({item_class: "nice", item_id: "id1"});
var item2 = new ItemModel({item_class: "sad", item_id: "id2"});

var ItemView = Backbone.View.extend({       
});

How should I implement the view so that the the views 'el's will translate to:

<div id="id1" class="nice"></div>
<div id="id2" class="sad"> </div>

In most examples I have seen, the view's el serves as a meaningless wrapper element inside which one has to manually write the 'semantic' code.

var ItemView = Backbone.View.extend({
   tagName:  "div",   // I know it's the default...

   render: function() {
     $(this.el).html("<div id="id1" class="nice"> Some stuff </div>");
   }       
});

So when rendered, one gets

<div> <!-- el wrapper -->
    <div id="id1" class="nice"> Some stuff </div>
</div>

But this seems like a waste - why have the external div ? I want the el to translate directly into the internal div!

Edit
Report

1 Answer

95

In your view just do something like this

var ItemView = Backbone.View.extend({
   tagName:  "div",   // I know it's the default...

   render: function() {
     $(this.el).attr('id', 'id1').addClass('nice').html('Some Stuff'); 
   }       
});
answered 2011-08-12T12:59:01.813

Your Answer