Thoughts of faith and development.

Tag: coding

  • TIL: Passing parameters to callback functions

    Today I tried to move an Event Listener callback function to it’s own module. It seemed simple enough. Take the following code example:

    app.js

    element.addEventlistener("submit", (event) => {
      event.preventDefault();
    });
    

    Now, my callback was a little more complex so it made sense to move to a module. The question then became why it didn’t work when I tried the following:

    app.js

    element.addEventListener("submit", eventHandler(event));
    

    eventHandler.js

    function eventHandler(event) {
      event.preventDefault();
    }
    

    I would get an error from app.js saying that event is not defined. After a little research I discovered on the MDN guide for addEventListener that you need to pass parameters using an anonymous function. My eventHandler() was fine – the issue was in the way I passed the parameter to the function in the callback. To fix it this was the solution:

    app.js

    // Arrow function syntax
    element.addEventListener("submit", (event) => {
      eventHandler(event);
    });
    
    // Full function syntax
    element.addEventListener("submit", function(event) {
      eventHandler(event);
    });
    

    Edit: turns out there is an even simpler approach when you’re only sending a single parameter – just don’t add the parameter to the callback function at all. This is also valid and you will still be able to access the parameter in the callback:

    element.addEventListener("submit", eventHandler);
    
  • The first post is the hardest

    Why do this blog? To make myself write thoughts and process what I learn as I grow my ability as a developer. I plan to write, even if it’s small and even if someone else wrote a better post about what I learned.

    Why public? I work for Automattic – a fundamentally distributed organisation who also make incredible Open Source software. We code in the open – you can find much of our code, issues and discussions publically so, why not learn to embrace that? Maybe someone will also learn something valuable along the way. Even if they don’t, I’ll still become a better blogger!

    Edit: how could I forget – we’re pretty heavily about WordPress so why wouldn’t I blog with it?

    I have no idea what I’ll post just yet so let’s enjoy the ride together. What I do know is that I plan to write a post at least once every month to start.

    Also…this post was written using the “Introduce yourself (Example post)” posts that are on WordPress sites by default. Whoever came up with that – you are amazing.