Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i use two different scope "this" in one function?

So i need to get the inner text of a given element through a Jquery event, and then set this text into a member of my class e.g.

myClass = function ()
{
    this.index = 0;

    this.onNavElementClick = function ()
    {
        this.index = parseInt(this.text());
    }

    this.myMain = function ()
    {
        $("nav#wow-so-much-inspiration").on("click", "a", this.onNavElementClick);
    }
}

myObject = new myClass();
myObject.myMain();

HTML:

<nav id="wow-so-much-inspiration">
    <a href="#">1</a>
    <a href="#">2</a>
    <a href="#">3</a>
</nav>

But this won't work because of the two different scopes inside the onNavElementClick() function... And i don't like the idea of doing _this = this, i'm pretty sure there is a right way to do that without doing MacGyver coding.

like image 683
Vulkhan Avatar asked Feb 11 '26 14:02

Vulkhan


1 Answers

jQuery event handlers also take the event object (including the target on which the event was triggered) as a first argument. Then you can use $.proxy to have your event handler bound to the outer this.

Something like this:

this.onNavElementClick = $.proxy(function (e)
{
    this.index = parseInt($(e.target).text());
}, this);
like image 195
Platinum Azure Avatar answered Feb 14 '26 05:02

Platinum Azure



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!