How do i get widget instance inside a jQuery widget?
I'm working on a keyboard widget for a project, i'm extending $.ui.mouse
. I need click behavior (not triggered by _mouseCapture). I'm having difficulties to get back this.options
inside it. See code blocks below :
$.widget("ui.keyboard", $.ui.mouse, {
widgetEventPrefix: "keyboard",
options: {
[...]
},
[...],
_create : function() {
this.element.bind('click.'+this.widgetName, this._mouseClick);
},
_mouseClick: function(e) {
// how do i get this.options here
}
});
Is it best to do this :
$.widget("ui.keyboard", $.ui.mouse, {
widgetEventPrefix: "keyboard",
options: {
[...]
},
[...],
_create : function() {
var self = this;
this.element.bind('click.'+this.widgetName, function(e) { self._mouseClick(e, self); });
},
_mouseClick: function(e, self) {
// how do i get this.options here -> self.options
}
});
Or this :
$.widget("ui.keyboard", $.ui.mouse, {
widgetEventPrefix: "keyboard",
options: {
[...]
},
[...],
_create :开发者_高级运维 function() {
this.element.bind('click.'+this.widgetName, this._mouseClick);
},
_mouseClick: function(e) {
var self = $.data(this, "keyboard");
// how do i get this.options here -> self.options
}
});
I had trouble with the last one when i try to trigger it manually $.data is not up unless i trigger a click on this.element
(which is quite logic).
Is there some other ways ? Which one is the best to pick ?
Thanks,
You could call an anonymous function returning an object, like this:
$.widget("ui.keyboard", $.ui.mouse, function(){
var self;
return {
widgetEventPrefix: "keyboard",
options: {
[...]
},
_create : function() {
self = this;
this.element.bind('click.'+this.widgetName, function(e) { self._mouseClick(e, self); });
},
_mouseClick: function(e, self) {
// do something with self.options
}
}
}());
This way you have access to self from within _mouseClick-
精彩评论