开发者

Call function from within jQuery plugin

开发者 https://www.devze.com 2023-02-12 17:34 出处:网络
I\'m modifying the lovely jquery.carousel.js plugin to have an autochange feature. I want to use setInterval() to call a function, but I can\'t get it to play nice.

I'm modifying the lovely jquery.carousel.js plugin to have an autochange feature. I want to use setInterval() to call a function, but I can't get it to play nice.

Here is the code I have at the moment:

autoSwitch: function()
{
    if(runAuto)
    {
        $('.next').click();
    }
},
init: function(el, options) {
    if(this.options.auto)
    {
        setInterval("this.('autoSwitch')", this.options.autoTime);
    }
}

This is just a snippet and there is other stuff, but I've left the important bits in. The line I'm having trouble with is setInterval("this.('autoSwitch')", this.optio开发者_JAVA百科ns.autoTime);. Whatever I try in the first argument of setInterval, it just doesn't work. So. Can you awesome people help me out as to how I call autoSwitch() from the setInterval() function please?


I think you're looking for jQuery.proxy:

init: function(el, options) {
    if(this.options.auto)
    {
        // Give `setInterval` a function to call
        setInterval(jQuery.proxy(this.autoSwitch, this)), this.options.autoTime);
    }
}

jQuery.proxy ensures that the function gets called with the correct context (this value). More about this general concept here: You must remember this

That's jQuery-specific. If you want a more general solution, you can use a closure:

init: function(el, options) {
    var context = this;    // Remember what `this` is in a variable
    if(this.options.auto)
    {
        // Give `setInterval` a function to call
        setInterval(function() {
            // The function is a closure that has access to
            // `context`, and so we can call it
            context.autoSwitch();
        }, this.options.autoTime);
    }
}

That uses a closure to bind the context (see: Closures are not complicated), which is the usual way to do this. jQuery.proxy just does a closure behind the scenes in a well-controlled environment so you know it's not closing over more data than you want it to.

0

精彩评论

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

关注公众号