0

What is an event object? When is it executed? Why do we have it? For example:

  1. when we use an anonymous function as in this example, the event object will not be renderPosts() function.

    window.addEventListener('DOMContentLoaded', () => renderPosts());
    
    const renderPosts = async () => {
      let uri = 'http://localhost:3000/posts?_sort=likes&_order=desc';
      const res = await fetch(uri);
      const container = document.querySelector(".blogs");```
    
    
  2. when we do not use anonymous function as in this example, the event object will be renderPosts() function.

    window.addEventListener('DOMContentLoaded',renderPosts());
    
    const renderPosts = async () => {
      let uri = 'http://localhost:3000/posts?_sort=likes&_order=desc';
      const res = await fetch(uri);
      const container = document.querySelector(".blogs");```
    
    
    

I do not see the difference and not really understand it.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Active Coder
  • 73
  • 1
  • 2
  • 8
  • 1
    [MDN](https://developer.mozilla.org/en-US/docs/Web/Events) has some useful information on the event object. Also, objects aren't "executed", functions are. – evolutionxbox Mar 23 '22 at 11:51
  • I think this might help you understand, https://www.30secondsofcode.org/articles/s/javascript-arrow-function-event-listeners, your callback is different in 1. and 2., that is the reason that Event is different. And Event is same as Event Object, if that is confusing. – onetwo12 Mar 23 '22 at 12:00
  • 2
    For `window.addEventListener('DOMContentLoaded',renderPosts());` see: [What is the difference between a function call and function reference?](https://stackoverflow.com/q/15886272) and [addEventListener calls the function without me even asking it to](https://stackoverflow.com/q/16310423) – VLAZ Mar 23 '22 at 12:01
  • 1
    In the second scenario you've just called the _renderPosts_ function, so it can not be added as an _event listener_ callback. Also event object is totally different from event listener callback function. You can check this out : https://www.w3schools.com/js/js_htmldom_eventlistener.asp – mahooresorkh Mar 23 '22 at 12:02
  • @Mark Schultheiss, thank you so much; you really solved all my confusions. All the resources are very helpful. – Active Coder Mar 23 '22 at 15:54
  • 1
    Credit to @VLAZ and others here for most of it, I just formatted the question a bit :) – Mark Schultheiss Mar 23 '22 at 16:27

0 Answers0