I'm trying to create a jQuery widget which extends from ui.slider. I'd like to have a custom method which executes on the 'slide' event. I tried overriding the parent's option just like when using the slider widget normally, but I ran into this problem with variable scopes:
$.widget( "ui.myslider", $.ui.slider, {
_create: function() {
this.foo = "bar";
// Outputs "bar"
this._mySlide();
// Outputs "undefined" when triggered
this.options.slide = this._mySlide;
$.ui.slider.prototype._create.apply(this, arguments);
},
_mySlide: function() {
alert(this.foo);
}
}
How can I trigger my function on the slide event AND have access to my variable?
Edit: Link to ui.slider source: https://github.com/jquery/jquery-ui/blob/master/ui/jquery.ui.slider.js
Edit: Solution
$.widget( "ui.myslider", $.ui.slider, {
_create: function() {
$.ui.slider.prototype._create.apply(this, arguments);
this.foo = "bar";
},
_slide: function() {
$.ui.slider.prototype._slide.apply(this, arguments);
alert(this.foo);
}
}
When we call jQuery.widget () it extends jQuery by adding a function to jQuery.fn (the system for creating a standard plugin). The name of the function it adds is based on the name you pass to jQuery.widget (), without the namespace - in our case "progressbar".
To allow for extension, $.widget() optionally accepts the constructor of a widget to use as a parent. When specifying a parent widget, pass it as the second argument - after the widget's name, and before the widget's prototype object. Like the previous example, the following also creates a "superDialog" widget in...
widgetEventPrefix: The prefix prepended to the name of events fired from this widget. For example the widgetEventPrefix of the draggable widget is "drag", therefore when a draggable is created, the name of the event fired is "dragcreate".
The jQueryUI Widget Factory is simply a function ($.widget) that takes a string name and an object as arguments and creates a jQuery plugin and a "Class" to encapsulate its functionality. Syntax. name − It is a string containing a namespace and the widget name (separated by a dot) of the widget to create.
In jQuery UI >= 1.9, you can use the _super
method instead:
_slide: function() {
this._super();
// equivalent to $.Widget.prototype._slide.call( this );
}
or superApply
:
_slide: function() {
this._superApply(arguments);
// equivalent to $.Widget.prototype._slide.apply( this, arguments );
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With