Using an external template, I am trying to render a Backbone JS view to the DOM. Unfortunately, I only get a blank screen, while checking with the console confirms that everything is working.
To get the rendered template in the DOM, I have to do something like $('body').append(myView.render().el);
, which according to many resources shouldn't be necessary. For example, this view from the TodoMVC project's Backbone implementation does not incorporate anything like $('body').append
, which makes me believe something in my code is wrong, but I can't find it.
The template in my HTML looks like this:
<script id="name-template" type="text/template">
<%= name %> (<%=age %>)
</script>
And this is the application code:
var App = App || {};
App.Models = {};
App.Views = {};
App.Models.Person = Backbone.Model.extend({
defaults: {
name: 'Peter',
age: 34
}
});
App.Views.Person = Backbone.View.extend({
tagName: 'p',
template: _.template($('#name-template').html()),
initialize: function() {
console.log(this.model);
}
});
App.personModel = new App.Models.Person();
App.personView = new App.Views.Person({model: personModel});
App.personView.render();
What do I have to change so that upon page load, the rendered template is added the DOM?
The short anwser is that the el
can point to a element that is already part of the DOM and if you do that you don't need to manually append it. To do this you can simple pass in the reference when you create your view instance, for example
App.personView = new App.Views.Person({model: personModel, el: '#someElement'});
App.personView.render();
Here's the slightly longer version.
A backbone el
is really just a reference to a DOM element whether it's already been attached to the page or not and it really isn't any different in this sense then a regular reference to a DOM element. Consider the following plain vanilla JavaScript code
var pElement = document.createElement("p");
var pElement = $('p'); //using jQuery
At this point pElement contains a reference to a DOM element but isn't attached to the page (yet). Anything you attach to this p
element won't be visibly until you attach it to the page using something like the following
document.body.appendChild(pElement);
$('body').append(pElement); //or using jQuery
If instead of creating a new p
element you instead got a reference to an existing element, any changes you made to that element would immediately be reflected on the page,
var pElement = document.getElementById('#myPElement');
var pElement = $('#myPElement'); //using jquery
At this point you can manipulate the pElement as you wish without attaching it to the page since it already is part of the page.