Setting id and className dynamically in Backbone.j

2019-03-07 13:22发布

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!

标签: backbone.js
8条回答
太酷不给撩
2楼-- · 2019-03-07 14:09

You can set the properties className and id on the root element: http://documentcloud.github.com/backbone/#View-extend

var ItemView = Backbone.View.extend({
   tagName:  "div",   // I know it's the default...
   className : 'nice',
   id : 'id1',
   render: function() {
     $(this.el).html("Some stuff");
   }       
});

EDIT Included example of setting id based on constructor parameters

If the views are constructed as mentioned:

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

Then the values could be set this way:

// ...
className: function(){
    return this.options.item_class;
},
id: function(){
    return this.options.item_id;
}
// ...
查看更多
劳资没心,怎么记你
3楼-- · 2019-03-07 14:10

Try to assign the values in initialize method this will directly assign id and class to the div attribute dynamically.

var ItemView = Backbone.View.extend( {
    tagName : "div",   
    id      : '',
    class   : '',

    initialize : function( options ) {
        if ( ! _.isUndefined( options ) ) {
            this.id = options.item_id;
            this.class= options.item_class;
        }
    },

    render : function() {
        $( this.el ).html( this.template( "stuff goes here" ) ); 
    }
} );
查看更多
登录 后发表回答