I’m writing a Javascript app that is getting an HTML document via AJAX, then needs to process it to attach event listeners (specifically, Bootstrap popovers) to the elements inside it. I’m having difficulty attaching the listeners, and I believe it’s a scope issue. Here’s the relevant code:
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); }});
...
The problem (I think) is the func() call in this.load. If I pass it this.process(), then it scopes the ‘this’ to the window, and there’s an error. If I pass this.process, it’s a lambda that’s created and it still fails. If I call this.func() the same problem occurs.
How do I either a) keep the scope within the App object with the callback, or b) reorganize this mess to call the handler after load?
I’d imagine you want to use the
var that=thisscoping trick on all of the methods: