0

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.

bluehallu
  • 10,205
  • 9
  • 44
  • 61
  • 3
    `bind()` is **not** deprecated. Deprecated is *different* to "preferred". [`live()`](http://api.jquery.com/live) is the ***only*** event method that is currently deprecated. [`change()` is a alias for `on('change')`](https://github.com/jquery/jquery/blob/754bda21cbc5c9044daf7f968fb9b4ffae39e334/src/event.js#L1040-1067), so use `change()` (or `bind()` if you want, as it's not deprecated). – Matt Jun 26 '12 at 09:26
  • 1
    Possible duplicate (to tons of question): http://stackoverflow.com/questions/8065305/whats-the-difference-between-on-and-live-or-bind. – VisioN Jun 26 '12 at 09:26

1 Answers1

1

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.

James Allardice
  • 164,175
  • 21
  • 332
  • 312
  • But the downside is that you are using strings. For example, there is no error when you mispell (misspell?) a string. – Esailija Jun 26 '12 at 09:34
  • @Esailija: But your `change` event handler also won't fire... should be pretty obvious to spot :P. – Matt Jun 26 '12 at 09:35
  • 1
    @Matt I meant in a more generic situation than a trivial single change handler... what if you have a more complex project than that ? And depending on what you have in the handler you have to determine if the handler didn't fire in the first place or if the handler has logic errors that make it do nothing. – Esailija Jun 26 '12 at 09:42
  • @Esailija: I see what you mean. If I'm honest it's never something I'd considered before! – Matt Jun 26 '12 at 09:43