I’m using backbone.js, underscore.js and jQuery. I took the following sample code from http://jsfiddle.net/thomas/C9wew/6/:
<!DOCTYPE html>
<html>
<head>
<title>backbone.js</title>
</head>
<body>
<div id="search_container">
Container
</div>
<script src="/js/jquery-1.7.2.min.js" type="text/javascript" charset="utf-8"></script>
<script src="/js/underscore-min.js" type="text/javascript" charset="utf-8"></script>
<script src="/js/backbone-min.js" type="text/javascript" charset="utf-8"></script>
<script type="text/template" id="search_template">
<label>Search</label>
<input type="text" id="search_input" />
<input type="button" id="search_button" value="Search" />
</script>
<script type='text/javascript'>
//<![CDATA[
$(window).load(function() {
SearchView = Backbone.View.extend({
initialize : function() {
this.render();
},
render : function() {
// Compile the template using underscore
var template = _.template($("#search_template").html(), {});
// Load the compiled HTML into the Backbone "el"
//this.el.html(template);
this.el.innerHTML = template;
},
events : {
"click input[type=button]" : "doSearch"
},
doSearch : function(event) {
// Button clicked, you can access the element that was clicked with event.currentTarget
alert("Search for " + $("#search_input").val());
}
});
var search_view = new SearchView({
el : $("#search_container")
});
});
//]]>
</script>
</body>
</html>
I’m expecting “el” to be a jQuery wrapped element, because is selected through a jQuery selector $(“#search_container”), however is not because it doesn’t have a function like html().
If I put a breakpoint at the line “el : $(“#search_container”)”, the “el” element has the function html(), which is the normal behavior. When the render function is called, the “el” element does not have anymore the html() function..any ideea?
The example you linked is based on an old version of backbone (0.3.3). Your sample probably uses the latest version (0.9.2) where
this.elis a DOM element andthis.$elis a cached jQuery|Zepto element associated withthis.el.This means that if you want to use the
htmlmethod, usethis.$el.html(template). Check this Fiddle http://jsfiddle.net/gFcRR/1/ for an updated example.