What is use of tagName, id, and className properties in Backbone View? While we can access dom element with el

26,483

Solution 1

Those properties are used if your view has to create its own element, that is, if it doesn't have a el attribute when instantiated (various reasons, I can go further in the matter). So you'll have a new element with the id id, classes className and attributes attributes.

You can find the relevant piece of code here. This _ensureElement method is used in the view's constructor.

Solution 2

All Backbone views have an el property Read doc here. If you do not pass an el while instantiating a view, it will create an empty DIV and use it.

  • Now, just say you do not want to use DIV as the container to render your view. You want it to be a UL instead. Just specify the tagName property for your view and it will be used instead.

  • If you want to add some css classes to your container, use className.

  • If you want to add some attributes to it (For example you want to add data-* attributes to your el) use the attributes property of Backbone view.

Share:
26,483
ali asad
Author by

ali asad

Updated on January 20, 2020

Comments

  • ali asad
    ali asad over 4 years

    Why do the properties tagName, id and className exist in a Backbone View?

  • Mbrevda
    Mbrevda almost 10 years
    As per the docs, attributes is used to create this.el: "this.el is created from the view's tagName, className, id and attributes properties, if specified". So you can also set attributes.class. It is NOT specifically for data-* attributes, although it can be used for that, as well as anything settable via jQuery.attr()
  • Alexander Mills
    Alexander Mills almost 9 years
    how do we render the custom element into the desired location in the DOM?
  • Alexander Mills
    Alexander Mills almost 9 years
    how do we render the custom element into the desired location in the DOM?
  • Rick
    Rick almost 5 years
    @AlexanderMills Just like you would add any other html into the DOM. Something like $("#container").html(myView.$el);