Search code examples
javascriptjquerybackbone.js

Backbone.js - render a new element to the page


Say you create a new element in your View - i.e. you don't target an existing element on the page with el.

var StudentView = Backbone.View.extend({
  tagName: 'article',
  className: 'student-name',
  template: _.template($('#name-tpl').html()),

  render: function(){
    var student_tpl = this.template({name: 'Rikard'});
    this.$el.html(student_tpl);
  }
});

You then instantiate the View and call its render method:

var student_view = new StudentView();
student_view.render();

Your HTML contains the following template:

<div class="target">
  <script id="name-tpl" type="text/template">
    <%= name %>
  </script>
</div>

This does not print the newly created element to the page. If we set el to .target, then it would work, but then it wouldn't print your tag name or class name that you set in the View.

Is there any way to print your newly created element to the page? I thought about using jQuery append, but it seems like there should be a more backbone-oriented solution.


Solution

  • Unless you use the el option to attach the view to an existing element in DOM, creates an HTMLElement in memory, detached from DOM. It's your responsibility to attach it to where you want (backbone creates a new element for you, but it doesn't know where in DOM you want it to be added).

    If you already have a Backbone.View and you want to set it to a different element, you can use setElement, but in this case as well, it is your responsibility to make sure that the element is part of DOM.


    If backbone gave you a way to specify the position of an element in DOM, that'd look something like:

    {
      tagName: 'article',
       elPosition: '#container > .content+div:nth-child(3)'
    }
    

    Again, there will be confusion like whether the element should be added before elPosition, or after etc. That looks ugly, no wonder why backbone leaves it to you rather than setting up more rules. In my opinion backbone sets less rules compared to other frameworks and give you more freedom (freedom can be a pain when you don't know what to do with it :)


    What we normally do is, have the main parent view point to the containing element in DOM like <body> , using the el option.

    Then append the child view's to it like this.$el.appendTo(parentView.$el);