我正在编写一个 Javascript 应用程序,它通过 AJAX 获取 HTML 文档,然后需要对其进行处理以将事件监听器(特别是 Bootstrap 弹出窗口)附加到其中的元素。我很难附加听众,我相信这是一个范围问题。相关代码如下:
var App = function(site){
this.load = function(data, func){
$('div.ajax').html(data);
func();
}
this.dispatch = function(data){
if(data.indexOf('from_server') !== -1){
this.load(data, this.process);
console.log('Loaded view from Matisse.');
return true;
}
}
this.process = function(){
this.popovers('from_server');
}
this.popovers = function(el){
var that = this;
$('img.artwork.gallery', el).each(function(){
$(this).popover({ trigger: 'hover', content: that.popoverPopulate(this) });
});
}
this.popoverPopulate = function(el){
return $(el).next('div.popover_content').html();
}
}
var APP = new App();
$.ajax({blah: blah, success: function(data){ APP.dispatch(data); }});
...
问题(我认为)是 this.load
中的 func()
调用。如果我将它传递给 this.process()
,那么它会将“this”限定在窗口中,并且会出现错误。如果我传递 this.process
,它是一个已创建的 lambda,但它仍然失败。如果我调用 this.func()
会出现同样的问题。
我该如何 a) 将范围保留在带有回调的 App 对象内,或者 b) 重新组织这个困惑以在加载后调用处理程序?
最佳答案
我假设您想对所有方法使用 var that=this
范围技巧:
var App = function(site){
var that = this;
this.load = function(data, func){
$('div.ajax').html(data);
func();
}
this.dispatch = function(data){
if(data.indexOf('from_server') !== -1){
that.load(data, that.process);
console.log('Loaded view from Matisse.');
return true;
}
}
this.process = function(){
that.popovers('from_server');
}
this.popovers = function(el){
$('img.artwork.gallery', el).each(function(){
$(that).popover({ trigger: 'hover', content: that.popoverPopulate(this) });
});
}
this.popoverPopulate = function(el){
return $(el).next('div.popover_content').html();
}
}
关于对象内的 Javascript 回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10098699/