2012-04-11 104 views
1

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

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.loadfunc()电话。如果我通过它this.process(),那么它将'this'范围限定到窗口,并且出现错误。如果我通过this.process,它是一个创建的lambda,它仍然失败。如果我打电话this.func()发生同样的问题。

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

回答

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(); 
    } 
} 
+0

接受,因为它排在第一位,但荣誉给伊利亚为好。当答案出现时,我已经这样做了,但谢谢。听众仍然没有附加,但我认为这是Bootstrap的问题,而不是我的Javascript。 – 2012-04-11 02:39:49

+0

啊,是的 - 我没有使用bootstrap,所以我不熟悉它的问题。祝你好运! (另外,我会第二个荣誉@伊利亚尔 - 两分钟不是没有。) – JKing 2012-04-11 02:45:25

1

这是指它是目前使用的上下文。所以当你做this.process它将会定位到窗口。如果您这样做App.load(data, App.process)那么它将针对App对象中的过程函数。

4

事情是这样的:

var App = function(site){ 
    var self = this; //-<!!! 

    this.load = function(data, func){ 

    ... 

    this.dispatch = function(data){ 
     if(data.indexOf('from_server') !== -1){ 
      self.load(data, self.process); 
    ... 
+1

哈哈哈,我真的很喜欢你的“注意这个”的评论!这很好。另外,在最后一行(在“...”之前),你可能想在方法调用时使用'self'而不是'this'以及你传入的引用,不是?或者'this'仍然是那个对象而不是'window'? – JKing 2012-04-11 02:28:24

+1

:-)你说得对。 – 2012-04-11 02:29:49