0

in jQuery function:
.on(event, [selector,] [data,] handler)

How jQuery parse this call:
on('click', 'tag3', () => {})
tag3 is selector or data?

Vasily Pozdeev
  • 239
  • 2
  • 7

2 Answers2

1

The last argument must be the handler. So if there are two arguments there there is no data and no selector.

If there are four arguments than the second one must be selector and the third one must be data.

So it only becomes tricky if there are exactly three arguments.

If the second argument isn't a string, then it can't be a selector, so it must be data.

If it is a string then it could be a selector or data. Now jQuery could do some heuristics by running it through the selector engine and seeing if it is a valid selector … but it doesn't. It just assumes that if the second argument is a string then it is a selector.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
0

How jQuery distinguish between 'data' and 'selector' parameter?

They have a different data-types

data - is a plain object (not a DOM or jquery object)

selector - is a string or a jquery/DOM/DOM-array object.

so, jquery can make out whether an argument is a selector or data by judging the properties of the argument, for example this and this

return obj instanceof HTMLElement; //to check if it is a DOM object

or

return obj instanceof jQuery; //to check if it is a jquery object

tag3 is selector or data?

As per documentation

If a string is passed as the parameter to $(), jQuery examines the string to see if it looks like HTML (i.e., it starts with ). If not, the string is interpreted as a selector expression, as explained above. But if the string appears to be an HTML snippet, jQuery attempts to create new DOM elements as described by the HTML. Then a jQuery object is created and returned that refers to these elements.

If the string passed to jquery method is an HTML then subsequent object is either a document (DOM object) or an attributes object.

Community
  • 1
  • 1
gurvinder372
  • 66,980
  • 10
  • 72
  • 94
  • "If a string is passed as the parameter to $()," — The question is asking about `on()` not `$()`. – Quentin Jun 20 '16 at 11:52
  • @Quentin oh, my bad. Anyways, upper half of the answer is still valid. `on()` also checks for the `typeof` argument value https://github.com/jquery/jquery/blob/58c6ca9822afa42d3b40cca8edb0abe90a2bcb34/src/event.js#L43 – gurvinder372 Jun 20 '16 at 12:17
  • Anyway, guys, thanks! I found out in source code, that it checks what if it 'string', so it's selector. If not - data – Vasily Pozdeev Jun 20 '16 at 12:41