Reputation: 4259
Note: the code looks long but its simple psuedo code for demo purpose. Don't flee!
I have written a widget that listens for key presses. When the onKeyDown
event is fired the reference to this
is lost. So I set a scoped variable called self
to reference the widget. self
is initalised when the widget is created.
This works but I'm not sure this is the right approach. I think the solution here is to do with a proxy? perhaps the self
variable is already acting as a proxy? anyone want to shed some light on whats happening?
(function($)
{
var vendorPrefix = Modernizr.prefixed("transform");
var self;
$.widget("ui.myWidget", {
_create: function()
{
self = this;
//Do some widget stuff
document.addEventListener('keydown', this.onKeyDown, false)
return this;
},
exampleFn: function()
{
},
onKeyDown: function(event)
{
// this now refers to "document" and not the widget
switch(event.keyCode)
{
case 37:
self.exampleFn();
break;
case 39:
self.exampleFn();
break;
}
}
});
})(jQuery);
Upvotes: 1
Views: 1266
Reputation: 10090
You can also use jQuery.proxy() if you'd like to get rid of the self
variable:
onKeyDown: $.proxy(function(event)
{
// this now refers to "document" and not the widget
switch(event.keyCode)
{
case 37:
this.exampleFn();
break;
case 39:
this.exampleFn();
break;
}
}, this)
Anyway, what's happening is that this
in a function refers to that function. So this
in onKeyDown
is onKeyDown
function. If you use a proxy like I did above, this
in onKeyDown
will become a reference to the parent function.
More on this
behavior in JavaScript: How does the "this" keyword work?
Upvotes: 1
Reputation: 5796
I'm not sure what you mean by proxy as there's no such thing in javascript, but no, it's not the right way of doing it as you've essentially created a global variable.
For instance, if the widget were initialized multiple times you would probably see some really weird behaviour depending on your code.
Get rid of the global var self
and move it to above the _create
method inside the object declaration so it's a private variable to that object.
Upvotes: 0
Reputation: 8183
This is because the "this" keyword refers to the object where the event is attached.
Using the self tip is a good choice.
Upvotes: 0