How to subclass a widget

jQuery UI 1.8 added the ability to extend the widget with the following code:

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

Now I can create a weirdbutton and it looks very much like a button:

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

However, only trifle events are triggered. Therefore, if I have something like

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

I will skip all the creation of weird buttons. This can be fixed by manually triggering the button events from the weird widget. Not really, but it works.

The big problem is that such code will not work:

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

The second line, rather than setting an option on an existing button, creates a new one. I do not know how to fix this.

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

+4
source share
1 answer

I do not know for the .bind approach, but replacing the original _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 (in the document):

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

you should get console.log

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

+3
source

Source: https://habr.com/ru/post/1342618/


All Articles