Following this tutorial went okay but I decided to give it another run with backbone 0.9 and the new setElement command.
<script type="text/javascript" id = "test" >
SearchView = Backbone.View.extend({
initialize: function(){
this.render();
},
render: function(){
var template = _.template( $("#search_template").html(), {} );
//Right here
this.setElement( template );
},
events: {
"click input[type=button]": "doSearch"
},
alert( "Search for " + $("#search_input").val() );
}
});
var search_view = new SearchView({ el: $("#search_container") });
</script>
Previously, I used this.el.html(template)
, but how do I use the new setElement command?
What I have there currently doesn't work, the search field that should appear does not.
From the Backbone.js v0.9 documentation:
setElement
The Backbone View "el" property represents the html portion of the view that will actually be rendered to the page. To get the view to actually render to the page your view will need to add it as a new element in the page or attach it to an existing element int the page.
The reason the code you used before worked was because you were setting the "el" property for the view in the constructor to attach to an existing element with an id of "search_container":
The method you used before:
worked because you were adding your template html to the existing element on the page.
When you used setElement in the following way:
you were actually overriding your existing value for "el" from the element with id of "search_container" to the html of your template. And since your template has not been added to the page or doesn't already exist your view will not display.
If you want to still use setElement and continue attaching it to the id "search_container", I would call it when you initialize your view:
This way you can cached "$el" reference later, like so:
Hope this helps!