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);