2011-08-28 29 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的不同