Tuesday, September 6, 2011

Extending jQuery-UI Widgets

I recently needed to extend the jQuery-UI AutoComplete Widget for a few custom features. The act of extending the Widget was relatively easy, but its not the entire story. Simply extending the jQuery-UI Widget will cause you to lose native functionality. Here is what I'm talking about...

Say I want to extend the jQuery-UI Widget...
$.widget("ui.myAC", $.ui.autocomplete, {
    myMethod : function(){
    },
    myOverride : function(){
        self.myOverride()
    }
});

Doing this allows me to instantiate my custom widget...
$("#myInput").myAC({});

However... the following wont work.
$("#myInput").myAC("search", "%");

Calling the widgets public methods will fail. A little debugging shows me that jQuery-UI doesnt think that method exists. Hmm... I extended a jQuery-UI Widget, but I lost the native methods. Boo!

Since jQuery-UI Widget extension has changed recently, Google didnt provide me with an obvious answer. However, I kept stumbling upon this thing called a Bridge.

Lets try it...
$.widget.bridge("myAC", $.ui.myAC);

Woot! I now have access to the native methods. Now my custom widget is fully functional.

I could attempt to explain all the different things $.widget.bridge does for us, but I'd do a poor job. Here are some folks that have already explained it.
Eric Hynds
Alex Sexton

No comments: