Setting id and className dynamically in Backbone.js views

后端 未结 8 1822
生来不讨喜
生来不讨喜 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: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'); }
    });
    

提交回复
热议问题