bluehallu
bluehallu

Reputation: 10285

bind() shouldn't be used, what about it's shortcuts?

From the bind() jQuery API:

As of jQuery 1.7, the .on() method is the preferred method for attaching event handlers to a document.

And from the change() jQuery API:

This method is a shortcut for .bind('change', handler).

But there's no mention that change() is not to be used as it says in the bind() one.

Is there any real benefit from using on() instead of bind() as of jQuery 1.7? Are change() and similar shortcuts using bind() or on() as of jQuery 1.7? Ultimately, should I use change() or on()?

Thanks in advance.

Upvotes: 0

Views: 96

Answers (1)

James Allardice
James Allardice

Reputation: 166021

The shortcut methods (e.g. .change()) simply call bind internally:

jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " +
"mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " +
"change select submit keydown keypress keyup error contextmenu").split(" "), function( i, name ) {

    // Handle event binding
    jQuery.fn[ name ] = function( data, fn ) {
        if ( fn == null ) {
            fn = data;
            data = null;
        }

        return arguments.length > 0 ?
            this.bind( name, data, fn ) : //Just call `bind`
            this.trigger( name );
    };
    //...

And bind simply calls on:

//...
bind: function( types, data, fn ) {
    return this.on( types, null, data, fn ); //Just call `on`
},
//...

So it's probably very marginally quicker to just call on yourself. In real terms, there will be no difference in speed, so just use the one you feel most comfortable with.

Upvotes: 1

Related Questions