如何使用“this”?在我的主干视图中
How do I use "this" in my Backbone View?
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
$.get()
里面的this
没有指向视图
试题:
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);
});
}
});
这是JavaScript的"动态this
"功能,如果你想在回调中使用"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);
});
}
相关文章:
- 将日期时间作为 JSON 发送将无法在我的视图中正确显示
- 为什么不't我的变量在我的控制器中填充后在我的视图中呈现
- 为什么我的视图没有显示在角度ui视图中
- 为什么我无法在我的视图中看到这个变量
- 为什么我的视图模型不起作用
- 如何在我的视图中打印JavaScript代码
- Knockout JS将我的视图模型创建更改为使用映射pulgin
- 如何使用JS函数在我的视图中显示ViewBag的值
- KnockoutJS 绑定在我的视图模型实际创建之前应用
- 我的视图模型不会根据 JSON 结果淘汰来增加数字
- 用AngularJS清理我的视图
- 为什么我的视图在骨干中的数组长度不正确
- Knockoutjs:如何将单个项目从可观察数组传递到我的视图模型中
- Ajax响应并没有改变我的视图模型
- 将参数从我的视图(页面)传递到我的js文件
- 无法使用逻辑从主干路由器路由到我的视图
- 在我的视图页面中实现两个select
- 通过添加“更改”方法,我的视图不再绑定到它
- 使用AngularJS在我的视图中的另一个json中渲染json
- json对象直接从我的视图HTML