user734063
user734063

Reputation: 569

Accesing $this from a nested function in jQuery?

I have a click handler function with another input handler function nested inside of it. I need to access (this) value of data-filter attribute at the end of the inner-function. But data-filter belongs to the outer function class. I'd like to access and manipulate it from the inner function. Of even have all the variables open to each other between those functions, if that is possible.

// click handler to check if a set of links are clicked
$optionLinks.click(function () { 

    // click handler to continually check for keyboard input   
    jQuery('input').bind('input propertychange', function() {
        jQuery('#output').html(jQuery(this).val());

        // grab user input, put in a variable
        var txtinput = jQuery('#output').html();

        // check if user input matches any tags     
        if (jQuery.inArray(content, tags) >= 0) {

            // if it does overwrite the data-filter attribute
            jQuery('#gallery_filter').attr('data-filter', txtinput);

            // set this variable which is used by the outer function
            var selector_<?php echo $unique_id;?> = jQuery(this).attr("data-filter"); 

        }   
    });

    //do other stuff

});

Upvotes: 1

Views: 115

Answers (2)

Joel Cornett
Joel Cornett

Reputation: 24788

Here are two common patterns for dealing with this:

one:

function outerFunction() {
   var outerThis = this; // Now we can access outerFunction via outherThis \o/
   (function innerFunction() {
      doSomethingWith(outerThis);
      outerThis === this; // False
   })();
}

two:

function outerFunction() {
    var outerThis = this;
    (function innerFunction() {
        doSomethingWith(this);
        outerThis === this; // True
    }).bind(this)(); 
}

Upvotes: 0

AyB
AyB

Reputation: 11665

You could save the outer element into a variable:

jQuery('input').bind('input propertychange', function() {
  var that = this;

And use it inside the other function as:

jQuery(that).attr("data-filter");

Upvotes: 2

Related Questions