【发布时间】:2012-04-11 01:25:12
【问题描述】:
我正在编写一个 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) 重新组织这个混乱以在加载后调用处理程序?
【问题讨论】:
标签: javascript jquery twitter-bootstrap jquery-events