var homeView = Backbone.View.extend({
el: $("#main_container"),
initialize: function(){
_.bindAll(this, 'render');
},
render:function(){
$.get('/home', {}, function(data){
console.log(data);
var tpl = _.template(home_container_temp, {});
this.el.html(tpl);
});
}
});
我想做一个ajax GET请求,然后设置数据。但我无法做到,因为我得到了:
Uncaught TypeError: Cannot call method 'html' of undefined
答案 0 :(得分:4)
this
内的 $.get()
不是指视图。
陷阱>
var homeView = Backbone.View.extend({
el: $("#main_container"),
initialize: function(){
_.bindAll(this, 'render');
},
render:function(){
var $el = this.el;
$.get('/home', {}, function(data){
console.log(data);
var tpl = _.template(home_container_temp, {});
$el.html(tpl);
});
}
});
答案 1 :(得分:0)
这是“动态this
”的JavaScript功能,如果您想在回调中使用“this”,请将其保留在回调之外的变量中:
render: function() {
var _this = this; // keep it outside the callback
$.get('/home', {}, function(data){
console.log(data);
var tpl = _.template(home_container_temp, {});
// use the _this variable in the callback.
_this.el.html(tpl);
});
}