1
votes

Just started with backbone.js and javascript. On my collection, I can listen for 'reset' event and make it call the 'render' function of my view(this). But I add the view into the DOM in my router like this:

$('#container').html(view.render().el)

I call render().el (which i assume returns some HTML text) and add it to my container div. Calling render on my view alone is useless. So why does my view update perfectly on 'reset' event which merely calls the render function (which is useless as it just returns self(a view object), the actual updating occurs in my router where the view's rendered el gets append into my container div)?

I am following a tutorial that why I know the answer, just don't know the reason behind it.

Thanks

1

1 Answers

1
votes

In $('#container').html(view.render().el) you insert the view's top-element to your #container -element, like so:

<div id="container">
  <div class/id="whatever-your-view-has-defined">
    <!-- THIS IS WHERE YOUR VIEW PUTS ANYTHING GOING TO $(this.el) or this.$el -->
  </div>"
</div>

So when you call render before the view's corresponding collection or model has finished it's fetch, you'll probably just insert the view's own element into the container. Now when your collection/model has done fetching and triggers a reset, the view renders again. I suppose your render looks something like this:

render: function() {

  // do something with $(this.el) or this.$el

  // loop through collection and insert something from each model to the view
  // OR
  // take the view's model and insert it to the view
  // I reckon the inserting is done with templates or jQuery manipulation

  //finally 
  return this; // return this to allow chaining render to other things like calling el
}

This basically means that your first render stages your view into the DOM and the one called after reset fills it out with content. You could forego the

$('#container').html(view.render().el)

part, if you for example set your view's id-property to be content, the view will automatically seek out the element with the identifier content to be it's element. But then all your view's content will be inserted directly into the content-element.

Hope this helped, comment if something is still unclear!