From the Backbone.js v0.9 documentation:
setElement
view.setElement(element)
If you'd like to apply a Backbone view to a different DOM element, use setElement, which will also create the cached $el reference and move the view's delegated events from the old element to the new one.
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":
var search_view = new SearchView({ el: $("#search_container") });
The method you used before:
$(this.el).html(template);
worked because you were adding your template html to the existing element on the page.
When you used setElement in the following way:
this.setElement( template );
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:
initialize: function(){
this.setElement( this.el );
this.render();
}
This way you can cached "$el" reference later, like so:
render: function(){
var template = _.template( $("#search_template").html(), {} );
this.$el.html(template);
}
Hope this helps!
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…