Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extending jquery ui widget - how to access parent event

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);
    }
}
like image 572
Eero Heikkinen Avatar asked Aug 09 '11 06:08

Eero Heikkinen


People also ask

How to extend jQuery with widget?

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".

How to add a parent widget to a widget?

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...

What is the use of widgeteventprefix?

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".

What is jqueryui Widget Factory?

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.


1 Answers

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 );
}
like image 124
ehynds Avatar answered Sep 20 '22 00:09

ehynds