How do subclass a widget

1.2k views Asked by At

jQuery UI 1.8 added the ability to extend a widget using code like this:

$.widget("my.weirdbutton", $.ui.button, {
});

Now I can create a weirdbutton and it works a lot like a button:

$("#myButton").weirdbutton();

However, only weirdbutton events get fired. So if I have something like

$(".button").bind("buttoncreate", function() { 
    console.log("a button was created"); 
});

I will miss all the creation of weirdbuttons. This can be fixed by manually triggering the button events from the weirdbutton widget. Not great, but works.

A bigger problem is that code like this will not work:

$("#mybutton").weirdbutton();
$("#mybutton").button("option", "text", "My New Text");

The second line, rather than setting an option on the existing button, creates a new one. I don't know how to fix this.

So, is there a way to make a subclassed widget that follows the Liskov Substitution Principle?

1

There are 1 answers

3
ant1j On

I don't know for the .bind approach but replacing the initial _create method can be done using this approach:

$.widget("my.weirdbutton", $.ui.button, {
    _create: function() {
       $.ui.button.prototype._create.call(this);
       console.log("a button was created");
    }
});  

Then if you do a (at document):

$(function() {
  $("#myButton").weirdbutton();      
});

you should get a console.log

Full code here: http://jsbin.com/icota4/11/edit