0

I was reading jquery on method and the method signature is .on( events [, selector ] [, data ], handler )

so this means basically it accepts 4 arguments

I didnt understand what is meant by events [(why opened square bracket) similarily here selector ] [ and here data ]

Community
  • 1
  • 1
SpringLearner
  • 13,738
  • 20
  • 78
  • 116

1 Answers1

2

It means those two parameters are optional. You can specify any of these combinations of arguments when calling .on():

.on( events, selector, data, handler )
.on( events, selector, handler )
.on( events, data, handler )
.on( events, handler )

Notice that if you specify both selector and data, they have to be specified in order. The general order of parameters has to be maintained in spite of the optionals.

Also, since JavaScript is dynamically-typed, whether or not you specify selector, which takes a string, will affect what type of value data can have (plain object, function, etc). See the comments for details.

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
  • 2
    It's worth to mention that `data` can't be `String` (because it will be treated as selector) if selector is not specified. [Fiddle example](http://jsfiddle.net/w3omvmoc/1/). And exotic case when `data` is a `Function` seems to work. – Regent Apr 04 '15 at 08:58
  • @Regent Yes, `data` can also be a function. http://stackoverflow.com/questions/29266604/why-doesnt-on-method-execute-the-first-handler – Ram Apr 04 '15 at 09:05
  • Also note that the handler parameter is (see the second function signature) also optional. So, this is totally valid too: `$('body').on('click)` (might not make much sense though). So, I suppose the only real source of confusion is that why is the optional arguments selector and data documented using brackets where as the optional handler argument is documented by giving the function two signatures. – Timo Apr 05 '15 at 07:53