Dealing with function scoping problems and transitioning to Arrow Functions

Currently, I am delving into the world of arrow functions and attempted to convert my code snippet below. Unfortunately, I have encountered a scope issue with funcCall and enterKey. My intuition tells me that utilizing an arrow function could potentially resolve this dilemma.

const pressKey = (funcCall, enterKey = 13) => {
    document.addEventListener("keydown", _onKeyDown);
}
const _onKeyDown = (e) => {
    if(e.keyCode === enterKey) {
        e.preventDefault();
        funcCall();
    }
}

Answer №1

In order to have access to funcCall and enterKey within the scope of pressKey, you must create _onKeyDown using closure:

function pressKey(funcCall, enterKey = 13) {
    function _onKeyDown(e) {
        if(e.keyCode === enterKey) {
            e.preventDefault();
            funcCall();
        }
    }
    document.addEventListener("keydown", _onKeyDown);
}

It shouldn't matter whether you use arrow functions or not in this case.

Answer №2

If you're looking for a closure from partial application, arrow functions are a great way to achieve this in a concise manner:

const _onKeyDown = (funcCall, enterKey) => e => {
    if (e.keyCode === enterKey) {
        e.preventDefault();
        funcCall();
    }
};

function pressKey(funcCall, enterKey = 13) {
    document.addEventListener("keydown", _onKeyDown(funcCall, enterKey));
}

It's worth noting that while arrow functions work well for this task, they are not the only option available. If you prefer traditional syntax or need a solution without ECMAScript 2015 features:

function _onKeyDown(funcCall, enterKey) {
    return function (e) {
        if (e.keyCode === enterKey) {
            e.preventDefault();
            funcCall();
        }
    };
}

function pressKey(funcCall, enterKey = 13) {
    document.addEventListener("keydown", _onKeyDown(funcCall, enterKey));
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a way to retrieve the list element that was added after the HTML was generated?

How can I reference a list element added using the append function in jQuery within my onclick function? See my code snippet below: $(function() { let $movies = $('#showList') let $m = $('#show') $.ajax({ method: 'GET ...

What is the process for including an additional bar in a Google bar chart?

Trying to enhance my google bar chart by adding an extra horizontal bar, but facing challenges in integrating it smoothly with the existing chart. JS Code <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script> ...

AngularJS Currency Converter - Converting Currencies with Ease

I have a question regarding the most efficient way to handle currency conversion on a webpage. Currently, I have multiple input fields displaying different currencies. When a user clicks on the currency conversion button, a modal popup appears. After the ...

The canvas's document.getElementById function is unable to find any matching element,

Hello everyone, I am currently diving into the world of javascript and trying to expand my knowledge. However, I have encountered a problem that has me stumped, and I could really use some assistance. While exploring, I came across this page: http://www.w ...

If I click on the datalist link option during an ajax append, I would like to be redirected

When I try to link after clicking an option in the appended AJAX, it does not seem to work as expected: More details: $('#input-friends').on('input', function () { var id = $('#input-friends').val(); $.ajax({ ...

The problem of OAuth redirect URIs in Facebook login with ReactJS

I am currently in the process of integrating Facebook login by referring to and https://www.npmjs.com/package/react-facebook-login The issue I am encountering is... If a Facebook account is not logged in on the browser, clicking the Facebook login bu ...

Having an issue with my application crashing and showing the message "[nodemon] app crashed - waiting for file changes before starting...". Does anyone know how to

mainapp.js const PORT = 3000 const express = require('express') const axios = require('axios') const cheerio = require('cheerio') const app = express() app.listen(PORT, ()=>console.log('Server running on port ${PORT} ...

Making certain parts of a select list text bold while keeping others in normal font in React

I need to create a select list that displays various products with their names and a count in bold. Here's my approach: To achieve this, I am populating an array called productInformation with each product name and its corresponding count like this: ...

How can a JavaScript function be triggered by Flask without relying on any requests from the client-side?

I'm in the process of setting up a GUI server using Flask. The challenge I'm facing is integrating an API that triggers a function whenever there's a change in a specific Sqlite3 database. My goal is to dynamically update a table on the HTML ...

Utilizing JavaScript, HTML, and CSS to incorporate images within circular frames

After finding inspiration from this question about rotating objects around a circle using CSS, I decided to modify the code to include images of Earth orbiting the Sun. The challenge was to make one image orbit another like a planet circling its star. Ear ...

The component 'createSvgIcon' from 'material-ui' is not available in the 'utils' module of '@material-ui/core'

After installing material-ui/lab to utilize the alert component, I encountered an issue when trying to import it using import Alert from '@material-ui/lab/Alert';. It failed to compile and threw the following error: ./node_modules/@material-ui/l ...

JQuery fails to retrieve accurate width measurements

Utilizing this code snippet, I have been able to obtain the width of an element and then set it as its height: $(document).ready(function(){ $(".equal-height").each(function(){ var itemSize = $(this).outerWidth(); cons ...

"Enhance your web development skills by mastering jQuery alongside the

It's curious that jQuery doesn't support the use of the "+" sign. You can see how it functions with "1" and "3", but not with "2+". Just hover your mouse over each div to experience it. <div id="div-2+"></div> JSFiddle $('a. ...

Exploring modern ES6 (AngularJS) features for enhanced services

I am encountering difficulties when trying to access Angular's built-in services like $http while creating a service with ES6. For instance, I am developing a "ResultsFinder" service that will make an AJAX call and then perform some operations. The i ...

Passing an arrow function as props results in an error of undefined

When passing event handler functions as props to child components, regular functions are received but not fat arrow functions. import React, { Component } from "react"; export default class FruitClass extends Component { bananaEvents = { color: thi ...

Error: The reference to Excel is not recognized

I am looking to develop an Office add-in using angularjs and angularjs-ui-router: <bt:Urls> <bt:Url id="Contoso.Taskpane3.Url" DefaultValue="https://localhost:3000/addin/test" /> </bt:Urls> The module name is app, and th ...

The console is showing the Ajax Get request being logged, but for some reason it is not displaying on the

Could someone please explain why this response isn't displaying on the page? $.ajaxPrefilter( function (options) { if (options.crossDomain && jQuery.support.cors) { var http = (window.location.protocol === 'http:' ? &apos ...

Tracking link clicks to monitor navigation away from a page using Mixpanel or Google Analytics

As I work on tracking an event that triggers when a user attempts to exit the website by clicking on a link. <a ng-click="bookingOutside(trip,0)" href="https://www.google.com" target="_blank"> <button type="button" class="externalBooki ...

send another response following the completion of the request.end()

I am facing challenges with writing the correct callback function. The situation involves a user making a request to "/city", which then triggers the server to make a request to a third-party service for data retrieval using http.request(). I successfully ...

Using Vue.js to dynamically change attribute values based on a condition

I am currently displaying a v-tippy in the following manner: <label v-tippy content="My content text"> Everything is functioning as expected, but now I want to display it based on a condition show_tip == true. Is there a way to achieve th ...