Access Widget instance from within nested map/object
I have a really annoying scope issue for my JQuery Widget. Essentially I need to access the widget instance (this) inside of my map/object `options`.
Is it possible to do this? Any advice how I can achieve this? See this
JSFiddle for a demo of the problem.
- $.widget( "my.myWidget", {
- // Below 'this.defCallback' will be undefined
- // How can I store 'this' (the widget instance) in a variable??
- options: {
- //accessObjectParent: this.instantiator,
- isUndefined: (this.defCallback === undefined), // this refers to the map/object
- // Can I access the maps 'parent'/instantiator?
- // this.instantiator.defCallback ???
- callback: this.defCallback // allow user to overwrite/provide custom callback
- },
-
-
- ....
-
-
- defCallback: function() {
- console.log('defCallback');
- }
- });
If I had a nested function I know I can easily solve this but I have a nested object/map which makes things difficult.
- function foo {
- var _this = this;
-
- ...
-
- var bar = function() {
- // easily access this
- _this.defCallback();
-
- ...
- }
- }
Usage:
- $('<div></div>')
- .myWidget(); // use defCallback
-
- $('<div></div>')
- .myWidget({
- callback: function() {
- ...
- }
- }); // use custom callback
How the callback function is 'bound' and called:
- _create: function() {
- this.element.click( this.options.callback );
- }