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 !
1 Answer 1
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.
var a = document.createElement("div"); //Don't expect this to appear as a child of #footer or something
document.getElementById("footer").appendChild(a) //Now it is, but we needed to know about #footer.
At best you could shorten the plumbing a little by making a method like .renderTo and then:
someView.renderTo( "#clients-section"); //Would call .render and append the views .el to "#clients-section" without the view having to know about it
.renderTomethod and thenclient_search_view.renderto("#clients_search_modal")but the view itself should not know about"#clients_search_modaltagNameand other attributes, but I guess I was wrong