Sunday, September 15, 2013

Hack on jQuery UI widget

If you are going build your own jQuery UI widget / plugin, you may face a problem like me, how to determine the entry and exit point of the widget.
Let's say your widget is something like a date picker, initially it is a input box, when you click on it or tab to it, it popup a picker for you, then if you click outside the input box or the picker, the widget hide the popuped picker. The life cycle is so straight forward, but actually you would find focusout and blur tell you nothing about the new focus target, so you can't treat these two event as a exit point of the UI widget.
If you bind a exit point on these two events, when you click from the input box to the popup picker, it must fire one pair of blur and focus event, which make you popup stuffs close once and immediate re-open again, cause a bad flicking visual effect to user.
So after I read every lines on the jQuery's Datepicker, I suggest a widget should be something like this (just pseudo code):
$.widget('myWidget', {
    _init : function(){
        // Bind the enter and exit event handler
        this._on(this.element, {
            'focus' : this._enter
        this._on(document, {
            'mousedown' : this._exit,
            'focusin' : this.exit
    _enter : function(event){
        // Entry point, create the popup picker
        this._picker = new Picker();
        // Append to some where below the input box
    _exit : function(event){
        if( != this.element &&
              // Exit point, remove popup picker

No comments:

Post a Comment