开发者

How to access attribute in jQuery callback func?

开发者 https://www.devze.com 2023-03-31 13:12 出处:网络
var some_name = { moving:false, show : function () { this.moving = true; $(\'element\').slideDown(5000, function ()
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

精彩评论

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

关注公众号