Setting id and className dynamically in Backbone.js views

后端 未结 8 1809
生来不讨喜
生来不讨喜 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:15

    You need to remove tagName and declare an el.

    'tagName' signifies that you want backbone to create an element. If the element already exists in the DOM, you can specify an el like:

    el: $('#emotions'),
    

    and later:

    render: function() { 
         $(this.el).append(this.model.toJSON());
    }
    
    0 讨论(0)
  • 2021-01-29 20:20

    I know it's an old question, but added for reference. This seems to be easier in new backbone versions. In Backbone 1.1 the id and className properties are evaluated in the function ensureElement (see from source) using underscore _.result meaning if className or id is a function, it will be called, otherwise its value will be used.

    So you could give className directly in the constructor, give another parameter that would be used in the className, etc... Plenty of options

    so this should work

    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({       
      id: function() { return this.model.get('item_id'); },
      className: function() { return this.model.get('item_class'); }
    });
    
    0 讨论(0)
提交回复
热议问题