We’re using Backbone.js in one of my team’s projects, and this is the first time I use it.
I’ve seen many times this kind of code (it’s coffeescript, but clear enough I think. @ means this.)
clients_view = new Homespa.Views.Orders.Clients.SectionView(collection: @options.clients)
@$("#clients-section").html(clients_view.render().el)
clients_search_view = new Homespa.Views.Orders.Clients.SearchView
@$("#clients_search_modal").html(clients_search_view.render().el)
Isn’t there a better way to do this? I would expect to just call render on my view, and then everything’s good, I shouldn’t have to get the html and append/replace it by hand.
Thanks for you time !
The view appending itself to the page automatically would require the view to have knowledge of outer world, knowledge of elements
that it doesn’t own. This is not good.
And it’s not backbone specific, you cannot just create an element and expect it to appear somewhere. It always needs to be inserted
on the page first.
At best you could shorten the plumbing a little by making a method like
.renderToand then: