对象中的Javascript回调

b. *_*eck 1 javascript jquery twitter-bootstrap jquery-events

我正在编写一个通过AJAX获取HTML文档的Javascript应用程序,然后需要处理它以将事件侦听器(特别是Bootstrap popovers)附加到其中的元素.我很难附加听众,我认为这是一个范围问题.这是相关的代码:

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); }});

...
Run Code Online (Sandbox Code Playgroud)

问题(我认为)就是func()打电话this.load.如果我传递它this.process(),那么它将'this'范围限定在窗口中,并且出现错误.如果我通过this.process,它是一个创建的lambda,它仍然失败.如果我调用this.func()同样的问题发生.

我如何a)使用回调将范围保持在App对象中,或者b)重新组织此混乱以在加载后调用处理程序?

JKi*_*ing 5

我想你想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();
  }
}
Run Code Online (Sandbox Code Playgroud)