[英]Backbone.js el error
我目前仍在学习boneer.js,但仍然很早就出错了:
Uncaught TypeError: Cannot call method 'html' of undefined
在此this。$ el.html(template);
<body>
<div id="search_container"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<script src="http://ajax.cdnjs.com/ajax/libs/json2/20110223/json2.js"></script>
<script src="http://ajax.cdnjs.com/ajax/libs/underscore.js/1.1.6/underscore-min.js"></script>
<script src="http://ajax.cdnjs.com/ajax/libs/backbone.js/0.3.3/backbone-min.js"></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">
$(document).ready(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 );
}
});
var search_view = new SearchView({ el: $("#search_container") });
});
</script>
</body>
为什么会发生此错误?
您正在将视图的el元素设置为
new SearchView({ el: $("#search_container") });
但是html中没有元素已经存在。 这是导致错误的原因,用这种方式定义el意味着您已经在页面上存在该元素,并将该元素分配为视图的容器。
将该元素添加到HTML
或按如下所示进行编辑
new SearchView();
因此默认情况下, el
会退回到div。
当您在JavaScript代码中引用DOM元素时,该元素必须已经可用-JS代码应在此元素创建后运行。 在这里,您在脚本执行后创建了要向视图的el
字段#search_container
div。 为了避免此类问题,请使用jQuery的ready
方法:
$(document).ready(function()
{
SearchView = Backbone.View.extend({
// ...
});
// ...
});
在创建HTML文档并准备使用所有元素之后,此方法将运行作为参数传递的函数。
另外,您使用的主干版本似乎无法自动管理$el
属性的值。 如果您需要使用此版本,请像下面这样更新initialize
方法:
initialize: function()
{
this.$el = $(this.el);
this.render();
},
这将手动将$el
设置$el
所需值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.