开发者

How do subclass a widget

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");
开发者_C百科

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?


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜