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
In
$('#container').html(view.render().el)you insert theview‘s top-element to your#container-element, like so: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:This basically means that your first render stages your view into the DOM and the one called after
resetfills it out with content. You could forego thepart, if you for example set your view’s
id-property to becontent, the view will automatically seek out the element with the identifiercontentto 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!