2011-08-28 31 views
2
var some_name = 
{ 
    moving:false, 

    show : function() 
    { 
     this.moving = true; 

     $('element').slideDown(5000, function() 
     { 
      this.moving = false; //How to access to attribute "moving" of class some_name? 
     }); 
    }, 
} 

代码问题。如何访问jQuery回调函数中的属性?

回答

6

您可以在回调函数绑定到当前环境:

$('element').slideDown(5000, $.proxy(function() { 
    this.moving = false; 
}), this); // "this" inside of the function will be this "this" 

jQuery.proxy


或者你可以这样做:

this是目前情况下,它的价值取决于如何调用函数。可以分配this到函数的变量以外,和使用该变量代替:

var that = this; 
$('element').slideDown(5000, function() { 
    that.moving = false; //use that instead of this here 
}); 
+1

'$ .proxy '在你的例子中,它是一个函数调用*在另一个函数调用的参数列表中,所以很容易错过第二个右元素'' - 如你演示的那样':p' –

+0

嘿嘿,很好听:) – arnaud576875

+0

如果你不需要从对象外部访问'移动',只要删除这个。在移动之前。当你访问你的'那个'时,它将以完全相同的方式工作......当你需要从回调中访问'this'时,这个答案是古典的。但是如果你只需要你不能从外部访问的访问变量,那就太过分了。 – Blacksad

0

使用moving代替this.moving(在两个OCCURENCES)

变量绑定到上下文中使用时,这样即使你的事件回调中,您可以访问上述变量。

+0

这将不允许对象的其他方法访问'移动' – arnaud576875

+0

只要将移动声明为方法外部,其他方法*将*具有访问权限。唯一的一点是'移动'将是一个私有变量。上面的解决方案可行,但在我看来这是过度的。 – Blacksad

+0

你将不得不将整个对象+移动变量包裹在一个IIFE中,以使它私人化 – arnaud576875

0

在事件回调,thisevent.target,或捕获事件的元素。

您可以关闭的优势,JavaScript和访问moving属性是这样的:

show : function() 
{ 
    var moving = true; 

    $('element').slideDown(5000, function() 
    { 
     moving = false; 
    }); 
}, 

注意,虽然,这moving将是生活在some_name

第一 moving的不同