对象内的 Javascript 回调

标签 javascript jquery twitter-bootstrap jquery-events

我正在编写一个 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/

相关文章:

javascript - 如何在 JavaScript 中以编程方式将字符串插入文本字段

html - 在 bootstrap 汉堡图标左侧添加电话和 map 图标

javascript - 使用 Javascript 客户端连接到 Java 中的 ServerSocket

javascript - 这行 JS 代码与 Java 的正确等价物是什么?

javascript - jquery-match-height 不适用于第一行

javascript - 使用前端表单/输入框和 ajax 更新帖子元,无需重新加载页面

javascript - bootstrap data-toggle ="tab"- 如何通过 JS 调用激活选项卡

html - <li> 标签有时无法正确显示(错误?)

java - 我们是否必须发布与 Controller 中的 pojo 对象具有完全相同字段的 json 对象?

Jquery UI 拖/放,一个 div 可以工作,另一个则不能。怎么修?