开发者

How to access attribute in jQuery callback func?

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

Question in code.


You can bind the callback function to the current context:

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

See jQuery.proxy


Alternatively you could do this:

this is the current context, it's value depends on how the function is called. You can assign this to a variable outside of the function, and use this variable instead:

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


Use moving instead of this.moving (in both occurences)

Variables are bound to the context when they are used, so even inside your event callback you can access the variables above.


In the event callbacks, this refers to event.target, or the element that captured the event.

You can take the advantage of closures in javascript and access the moving attribute like this:

show : function ()
{
    var moving = true;

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

Note, though, that this moving will be different of the first moving that lives in some_name

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜