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!
You can set the properties
className
andid
on the root element: http://documentcloud.github.com/backbone/#View-extendEDIT Included example of setting id based on constructor parameters
If the views are constructed as mentioned:
Then the values could be set this way:
Try to assign the values in initialize method this will directly assign id and class to the div attribute dynamically.