开发者

Variables in a setTimeout function (jQuery)

I'm trying to use a jQuery statement inside a setTimeout function, but I don't get it to work. I tried a lot of variants, like this one (I'm us开发者_JS百科ing 'this' because the setTimeout is inside an each function, and the selector is cached/stored in an object, thus the $selector):

setTimeout("" + this.$selector + ".val('" + this.savVal + "')", 1);

How do I have to write this?

Thanks!


When you need to preserve the current this item when calling setTimeout use this structure:-

setTimeout((function(self) {
  return function() { $selector.val(self.savVal) };
})(this), 1);

This creates a closure from the outer functions execution context. The outer function returns an inner function that will have access the self parameter. Its the inner function that gets called when the timeout occurs yet the value of self will hold on to the original this value.


AnthonyWJones provided a great answer, but there's another similar one, which is slightly easier to write and read. You simply store the value of "this" in a local variable., ie.

var storedThis = this;
setTimeout(function() { $selector.val(storedThis.savVal); }, 1);


You could probably do something like this, if the variables you are trying to use are defined in each step of the loop.

var myObj = {
  $selector: myConfigObj.$myCachedSelector
}

$.each([ myObj, mySecondObj, myThirdObj ], function(n, $selector) {
    setTimeout(function() {
        $selector.val(saveVal);
    }, 1);
});


thanks for your answers.

I'm using a function inside the setTimeout now. But I found out that the real problem lies elswhere: in the each-function I'm trying to access object properties which are pointing to properties within a config object, but the result (for example for this.$selector) is "undefined".

var myObj = {
  $selector: myConfigObj.$myCachedSelector
}

$.each([ myObj, mySecondObj, myThirdObj ], function() {
    //code
});                 

Not sure what the problem is. Both objects are in the same function/scope.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜