Setting id and className dynamically in Backbone.js views

后端 未结 8 1814
生来不讨喜
生来不讨喜 2021-01-29 19:24

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

8条回答
  •  野的像风
    2021-01-29 20: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;
    }
    // ...
    

提交回复
热议问题