Reputation: 3332
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/:
Upvotes: 3
Views: 604
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
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
Reputation: 46323
It is how the prop()
function is defined in jQuery. Or more accurately, how the callback for prop()
is defined.
Upvotes: 1
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