How can you access a function from within another function in the same object while keeping the object structure largely intact?

Seeking a solution using JavaScript (ES6), I am in need of referencing a handler function called onKeyup. This will allow me to both add and remove an event listener in two functions that are declared within the same object.

Can you suggest how I can access the onKeyup function from the bind and unbind functions within the object? :

export default {
    bind(el) {
        let privateVar = 42;

        function foobar() {
            console.log('Foobar hit', privateVar);
        }

        function onKeyup() {
            console.log('onKeyup hit');
            foobar();
        }

        el.addEventListener("keyup", onKeyup, false);
    },

    unbind(el) {
        //`onKeyup` does not exist here, how can I fix that?
        el.removeEventListener("keyup", onKeyup, false);
    }
}

Is there a feasible way to achieve this?

One initial approach would involve modifying the code as follows, however, it may lead to decreased readability :

export default {
    privateVar : null,

    onKeyup() {
        console.log('onKeyup hit');
        this.foobar();
    },

    foobar() {
        console.log('Foobar hit', this.privateVar);
    },

    bind(el) {
        this.privateVar = 42;
        el.addEventListener("keyup", this.onKeyup, false);
    },

    unbind(el) {
        el.removeEventListener("keyup", this.onKeyup, false);
    }
}

Do you have suggestions for a better, cleaner approach?

Note: The structure of the bind and unbind functions within the object cannot be altered, as it is utilized as a directive declaration for Vue.js 2.*.

EDIT:

I also attempted an alternative organization of my code:

export default {
    onKeyup : null,

    bind(el) {
        let privateVar = 42;

        function foobar() {
            console.log('Foobar hit', privateVar);
        }

        this.onKeyup = function() {
            console.log('onKeyup hit');
            foobar();
        };

        el.addEventListener("keyup", this.onKeyup, false);
    },

    unbind(el) {
        el.removeEventListener("keyup", this.onKeyup, false);
    }
}

...however, this resulted in the error message:

Uncaught TypeError: Cannot set property 'onKeyup' of undefined

Answer №1

An efficient way to protect your code and only expose specific functions is by using an Immediately Invoked Function Expression (IIFE). This IIFE encapsulates everything and allows you to only reveal the bind() and unbind() functions.

export default (function() {
    var privateVar;

    function onKeyup() {
        console.log('onKeyup executed');
        foobar();
    }

    function foobar() {
        console.log('Foobar executed', privateVar);
    }

    function _bind(el) {
        privateVar = 42;
        el.addEventListener("keyup", onKeyup, false);
    }

    function _unbind(el) {
        el.removeEventListener("keyup", onKeyup, false);
    }

    return {
        bind:_bind,
        unbind:_unbind
    };
})();

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

The form validation feature is not functioning as expected when integrating mui-places-autocomplete with MUI React

I'm currently working on implementing an autocomplete feature using Google Places API in my project with Material UI React, Redux-Form, Revalidate, and MUI-Places-Autocomplete. Although I've successfully integrated the place lookup functionality, ...

Turn off scrolling for the body content without removing the scrollbar visibility

Whenever I click a thumbnail, a div overlay box appears on top: .view-overlay { display:none; position:fixed; top:0; left:0; right:0; bottom:0; overflow-y:scroll; background-color:rgba(0,0,0,0.7); z-index:999; } Some browsers with non-f ...

Reinstall software using the information in the package-lock.json file

Imagine this situation: I added certain libraries like jquery and bootstrap using the command npm install. As a result, npm created a package-lock.json file which contains information about the installed packages. When I uploaded my project folder to a g ...

The alias for the last item in a nested ng-repeat loop will consistently evaluate to true

Within my code, I am utilizing two nested ng-repeat functions and I am looking to change the $last variable to something different for each level - let's say outerLast and innerLast. I attempted to achieve this by using ng-init="outerLast= $last" and ...

Can a "fragile export" be generated in TypeScript?

Testing modular code can be challenging when you have to export things just for the purpose of testing, which can clutter your code and diminish the effectiveness of features like "unused variable" flags on compilers or linters. Even if you remove a usage ...

Determine ng-checked according to an array

I am working with a select dropdown that creates checkboxes using ng-repeat based on the selected value. The goal is to have all values in the dropdown selected, corresponding checkboxes checked, and store them in an array. Each time a checkbox is changed ...

unable to locate the allong.es variadic function

Encountering an Error node.js:201 throw e; // process.nextTick error, or 'error' event on first tick ^ TypeError: undefined is not a function at /home/ubuntu/nodejs/test.js:4:10 at factorial (/home/ubuntu/nodejs/test.js:17: ...

Only users who are logged in to Node.js can access the message

Whenever users are online and do not close our clients like a browser tab or android application, I have the ability to send a message to each specific user by utilizing the following code: socket.broadcast.to(socketId) .emit('new message', ...

AngularJS not refreshing the view

I'm having an issue in my app where I calculate the total bill and display it on my view. The first time, everything works fine. However, when I increment the $scope.bill_total, the view is not updating even though I can see the change in the console. ...

vue-chat-scroll failing to auto scroll to the bottom of the message list

In my Vue application, I have implemented a chat feature where messages are displayed in a list structured as follows: <div class="chat"> <ul v-chat-scroll> <li v-for="message in messages" ...

Anomaly in the default checked state of checkboxes

I'm currently working on a project and encountering an issue with the code below. I need to incorporate a forEach() loop within getElements() instead of using map(). Additionally, I want the default state of a checkbox to remain checked even after nav ...

Building a new Vue.JS component inside of an existing parent component

Trying to create a nested component in VueJS has been a bit challenging for me. I have attempted something like this, but unfortunately, it doesn't seem to work as expected (the child component does not display anything): I am interested in exploring ...

Having Trouble with $.ajax Function in my Program

After spending three days experimenting with various methods, I'm still unable to successfully use the Javascript ajax command to send form values to a php script. Despite no errors being displayed and the scripts running smoothly, nothing is getting ...

Exploring the process of sending props via the render method in Vue.js and observing their behavior

Struggling with passing a prop from a parent component down to a child created using CreateElement/render in vue.js and then watching it. Here is the parent component: Vue.component('my-drawing', MyDrawing) new Vue({ el: '#drawing' ...

Ways to eliminate submenu tooltips

Whenever I hover over a menu item with submenu pages in the wordpress backend, a "tooltip" pops up showing each submenu page. How can I remove these tooltips? I have attempted to remove the wp-has-submenu style class, which somewhat works. The tooltip no ...

Improving functions in vue.js

Currently working on my personal project, which is an HTML website containing tables generated through vue.js. I believe that my code could be simplified by refactoring it, but I am unsure about where and what changes to make. Below is the section of the c ...

What could be the reason that the painting application is not functioning properly on mobile devices?

I am facing an issue with my painting app where it works perfectly on desktop browsers but fails to function on mobile devices. I tried adding event listeners for mobile events, which are understood by mobile devices, but unfortunately, that did not solve ...

How to effectively handle a Lerna monorepo containing packages designed for both Vue 2 and Vue 3

I am currently working on creating a pull request to contribute to an open-source library that utilizes Lerna to manage multiple packages and npm as the package manager. Within the library, there is already support for Vue 2 through the existing package s ...

`Upkeeping service variable upon route alteration in Angular 2`

Utilizing a UI service to control the styling of elements on my webpage is essential. The members of this service change with each route, determining how the header and page will look. For example: If the headerStyle member of the service is set to dark ...

Having trouble transmitting a file from the frontend to the server in your MERN project?

Struggling to transfer an image file from the React frontend to the server and encountering issues with sending the file: Below is the front end code snippet: useEffect(()=>{ const getImage=async ()=>{ if(file){ ...