Please see the following fiddle.
HTML
<script id="person" type="text/x-handlebars-template">
<div>Title : {{title}} </div>
<div>First Name : {{firstname}}</div>
<div>Last Name : {{lastname}}</div>
</script>
<div id="people"></div>
JS
(function ($) {
var personTemplate= Handlebars.compile($("#person").html());
var Person= Backbone.Model.extend({
title: null,
firstname : "",
lastname : ""
});
PersonView = Backbone.View.extend({
tagName: "div",
template: personTemplate,
render: function () {
$(this.el).html(this.template(this.model));
return this;
}
});
$(document).ready(function () {
var AppView = Backbone.View.extend({
initialize: function () {
var passView = new PersonView (
{ model: new Person({ title: "Mr",
firstname : "John",
lastname : "Smith"})
});
$('#people').append(passView.render().el.outerHTML);
}
});
var App = new AppView();
});
})(jQuery);
I’ve created a basic mode and view, but the parameters for the view are not being picked up by the template. If i set the value directly on the person model, it finds them. But not if i set them via a new instance of the mode (or even if I use the init methods to .set() them.
What am I doing wrong?
In order to get a object for use with your template you need to call your model’s toJSON method.
For example
If you inspect one of your models in Firebug (or just output it to the console) you’ll notice that there are a lot more attributes then just the ones you specified, and that the values you specify are actually contained under a property attributes, calling
toJSONreturns an object with the models “values” that you specified.