How can I use two different "this" scopes in one function?
So, I need to get the inner text of a given element via a JQuery event and then set that text to a member of my class for example.
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 that won't work because of the two different scopes within the function onNavElementClick()
... And I don't like the idea of ββdoing _this = this
, I'm sure there is a correct way to do that without MacGyver coding.
source to share
JQuery event handlers also accept the event object (including target
where the event was triggered) as the first argument. Then you can use $.proxy
to bind the event handler to the external one this
.
Something like that:
this.onNavElementClick = $.proxy(function (e)
{
this.index = parseInt($(e.target).text());
}, this);
source to share
You can use the method bind
, but I believe this has proven to have minor performance implications.
An example is what the $ .proxy response does.
var myClass = function ()
{
this.index = 0;
this.onNavElementClick = (function (event) {
this.index = parseInt( $(event.target).text() );
}).bind(this);
this.myMain = function ()
{
$("nav#wow-so-much-inspiration").on("click", "a", this.onNavElementClick);
};
}
var myObject = new myClass();
myObject.myMain();
Another option is to use call
or apply
with a simple wrapper function.
var myClass = function ()
{
this.index = 0;
this.onNavElementClick = function (event)
{
this.index = parseInt( $(event.target).text() );
};
this.myMain = function ()
{
var self = this;
$("nav#wow-so-much-inspiration").on("click", "a", function (event) {
self.onNavElementClick.call(self, event);
});
};
}
var myObject = new myClass();
myObject.myMain();
source to share