开发者

Why are "autocompleteselect" handlers called before the configured "select" handler?

开发者 https://www.devze.com 2023-03-01 16:12 出处:网络
I am building a customized autocomplete widget in which I need to override the default \"select\" behavior and have it run before any externally attached event handlers.

I am building a customized autocomplete widget in which I need to override the default "select" behavior and have it run before any externally attached event handlers.

$("#input").autocomplete({
    source: ['A','B','C'],
    select: function() {
        console.log("from config.select");
    }
});
$("#input").bind("autocompleteselect", function(event, ui) {
    console.log("from bind()");
});

When I select an element from the resulting autocomplete, the following gets prin开发者_如何学运维ted to my console:

from bind()
from config.select

My question is, why? Is there some rationale behind this? It seems to me that the event handler configured in the settings/config object given to the autocomplete() "constructor" should happen first, and the handlers attached with bind() should happen afterwards.

I realize that I can just use bind() within my plugin to ensure that my event handler is the first one run, but it adds some clutter to the code.


That's because behind the scene it uses the _trigger function of the Widget object.

Check out code excerpt bellow and you'll see that the callBack (the function in your options parameter) is called after the normal event trigger (this.element.trigger).

_trigger: function( type, event, data ) {
    var callback = this.options[ type ];

    event = $.Event( event );
    event.type = ( type === this.widgetEventPrefix ?
        type :
        this.widgetEventPrefix + type ).toLowerCase();
    data = data || {};

    // copy original event properties over to the new event
    // this would happen if we could call $.event.fix instead of $.Event
    // but we don't have a way to force an event to be fixed multiple times
    if ( event.originalEvent ) {
        for ( var i = $.event.props.length, prop; i; ) {
            prop = $.event.props[ --i ];
            event[ prop ] = event.originalEvent[ prop ];
        }
    }

    this.element.trigger( event, data );

    return !( $.isFunction(callback) &&
        callback.call( this.element[0], event, data ) === false ||
        event.isDefaultPrevented() );
}

Best regard,
Stéphane.

0

精彩评论

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