4

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?

Community
  • 1
  • 1
itsadok
  • 28,822
  • 30
  • 126
  • 171

1 Answers1

3

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

ant1j
  • 305
  • 2
  • 18
  • The problem is that `console.log` is called by the **user** of my plugin, not me. I don't know what they'll really want to do (logging is just an example), and I can't hard-code it into the widget code. – itsadok Mar 10 '11 at 13:06
  • Thanks ant1j, I didn't knew how to call the original create-method of the superior class! – acme May 30 '11 at 08:29
  • 1
    Do not forget to mark your question as "answered" if it's the case! – ant1j May 30 '11 at 10:49