Shan Khan
Shan Khan

Reputation: 10369

How to access variable from Closure Scope in JavaScript

How to access the closure scope variables in inner function in JavaScript.

I want to access UL variable in setTimeout function.

    ul.find("li").each(function (a, ele) {

        $(ele).attr("tabindex", options.items[a].tabindex);

        $(ele).on("focusout", function () {

            setTimeout(function () {
                **//ACCESS UL HERE**
                debugger;
            }, 1);

        }.bind(ul,ele));
    }.bind(ul));

Upvotes: 1

Views: 787

Answers (3)

Rayon
Rayon

Reputation: 36609

Using closure in setTimeout

Closures 'remember' the environment in which they were created.

ul.find("li").each(function(a, ele) {
  $(ele).attr("tabindex", options.items[a].tabindex);
  $(ele).on("focusout", function() {
      setTimeout(function(ul) {
        return function() {
          console.log(ul);
        }
      })(ul), 1);
  }.bind(ul, ele));
}.bind(ul));

Upvotes: 1

Anoop Joshi P
Anoop Joshi P

Reputation: 25537

You can use access the UL by finding the parent of current element. For getting the immediate parent with specified type, you can use .closest() method

$(ele).on("focusout", function() {
   var el = $(this);
   setTimeout(function() {
     el.closest("ul");
     debugger;
   }, 1);

 }.bind(ul, ele));

Upvotes: 0

Praveen Kumar Purushothaman
Praveen Kumar Purushothaman

Reputation: 167250

It works normally. The scope of the ul is valid inside the setTimeout function.

ul.find("li").each(function() {
  $(this).attr("tabindex", options.items[a].tabindex)
    .on("focusout", function() {
      setTimeout(function() {
        ul.css('color', 'orange');
      }, 1);
    });
});

A simple code like this will explain you:

(function s() {
  var a = "hi";
  setTimeout(function () {
    console.log(a);
  }, 1000);
})();

Here, the ul is the same as the a variable.

Upvotes: 0

Related Questions