Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialvamosrope14
14,932 PointsWhy couldn't we just put getJSON as a callback reference in the addEventListener method?
.
2 Answers
highlandcow
7,352 PointsI actually got hung up on this question myself and couldn't come up with a good explanation other than "addEventListener expects a function declaration rather than a function invocation" which is either a gross oversimplification or plainly wrong (but conveniently gets me to the next video). Hoping someone in the community can chime in with a good explanation, perhaps with a simple example. Thanks!
Farid Lavizadeh
12,006 PointsUnless a named function is tied to an event, it will just run without the event occurring. Since getJSON(astrosUrl) is not tied to any event, it will run before a user clicks anything. To tie the named function to an event, a preceding anonymous function is used.
highlandcow
7,352 Pointshighlandcow
7,352 PointsI reviewed the "Callback Functions in JavaScript" course. Someone touched on this topic in the discussion on one of the videos: "When you put parentheses after a function name (with or without arguments), you are invoking ("calling") the function immediately and passing the function's return value as the argument. But for a callback, you want to pass the function itself, so it's important to not use the parentheses." Helped clear this up for me.