aless80
aless80

Reputation: 3332

Explanation for index and value inputs to anonymous function in javascript

I have a question on how anonymous functions work in Javascript. I saw this beautiful piece of code to toggle "disabled" from an html element [from this post link to stack overflow ]:

$('#el').prop('disabled', function(i, v) { return !v; });

The inputs to the anonymous function i and v are the index and the value.

Why is that? Is it because of .prop() or is this somehow a property of the anonymous functions? Are there other inputs available? Thanks

SOLUTION: The answer to my question is in the docs for .prop() api.jquery.com/prop/:

enter image description here

Upvotes: 3

Views: 604

Answers (4)

guest271314
guest271314

Reputation: 1

Why is that? Is it because of .prop() or is this somehow a property of the anonymous functions? Are there other inputs available?

No, not "properties" of anonymous function , parameters of anonymous callback function. Yes, additional parameters could possibly be defined for, passed to, called at function.

i : index is index of elements from selector #el passed ; v : value is value of disabled property of selected DOM element #el disabled

Upvotes: 1

taxicala
taxicala

Reputation: 21759

the anonymous function is passed as a paremeter to the jquery prop method (callback). jquery will do its magic behind and call that function passing those parameters to it in order to you be able to work with them.

Upvotes: 0

Amit
Amit

Reputation: 46323

It is how the prop() function is defined in jQuery. Or more accurately, how the callback for prop() is defined.

Upvotes: 1

Pointy
Pointy

Reputation: 413682

It's just how the jQuery .prop() method is implemented. If it sees that the second parameter is a function, it calls your function for each matched element, passing the element index and the attribute value.

Inventing an API in JavaScript involves making decisions like that for all situations involving a callback that the API clients will use. There are no hard-and-fast rules in general, though some contexts have conventions that should probably be followed when possible. An example is the Node world, where it's very common for callbacks to get passed two arguments, a (possibly null) error and the data relevant to the operation.

Upvotes: 1

Related Questions