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

Error encountered: When implementing mergeImages in express.js, a ReferenceError occurs stating that the window is not

I am encountering an issue while using mergeImages on my express.js server. The error message "ReferenceError: window is not defined" is displayed, but I am puzzled because I have not used the word 'window' in my code at all. Could you please rev ...

Attaching a $UI element to a <div> tag with JQuery may result in unexpected errors and issues

Attempting to connect SagePayments card elements to the paymentDiv. Followed their sample project for guidance, but encountering issues with populating the elements when running the program with a custom Sandbox merchantID and merchantKey. Chrome's de ...

Tips for maintaining the menu state following a refresh

Is there a way to save the menu state when pressing F5? I'm looking for a similar functionality as seen on the Binance website. For example, clicking on the Sell NFT's submenu and then refreshing the page with F5 should maintain the menu state on ...

Adding a promise to an array using Javascript

I am facing an issue while attempting to create an array of promises and then calling them using Promise.all. The problem lies in correctly pushing the functions into the array. It seems like they are getting executed instead of being inserted and waiting ...

Despite the session being expired, the Laravel API call still goes through successfully

My application is built as a Single Page Application using Laravel 5.8 and Vue 2.0. Currently, everything seems to be functioning smoothly, perhaps a bit too well. I noticed that even after deleting the session, I am able to perform actions such as saving ...

Dependency on the selection of items in the Bootstrap dropdown menu

I am currently struggling with a few tasks regarding Bootstrap Dropdown Selection and despite looking for information, I couldn't find anything helpful. Check out my dropdown menu Here are the functions I would like to implement: 1) I want the subm ...

Create a table within the B-Col element that automatically adjusts its size to match the column width using Vue-Bootstrap

Within my Vue component, I have the following code snippet: <b-modal ...> <b-row> <b-col sm="12"> <table > <tr v-for=... :key="key"> <td><strong>{{ key }}: </str ...

Troubleshooting Angular 2: Instances of Classes Not Being Updated When Retrieving Parameters

I am facing an issue with the following code snippet: testFunction() { let params = <any>{}; if (this.searchTerm) { params.search = this.searchTerm; } // change the URL this.router.navigate(['job-search'], {q ...

The elements within the Popup Modal are not displaying as expected

I found a helpful tutorial that teaches how to display a Popup Modal Window when the page loads. However, I'm facing an issue where the modal is not showing the contents and images properly. The code I am working on can be found at jsFiddle. My goal ...

Incapable of modifying the text within a div container

I am currently working on a script that translates a Russian forum word by word using TreeWalker. However, there is a specific type of div element that I have been unable to change the text for. That leads to my question: How can I go about changing it? Un ...

Troubleshooting issue with the spread operator and setState in React, Typescript, and Material-ui

I recently developed a custom Snackbar component in React with Material-ui and Typescript. While working on it, I encountered some confusion regarding the usage of spread operators and await functions. (Example available here: https://codesandbox.io/s/gift ...

Session-based Authorization

I'm completely new to working with express.js, and I've been facing an issue while trying to create a session-cookie after logging in. Even though I can initiate the session and successfully log in, the session data doesn't carry over to the ...

The Process of Developing Applications

As a newcomer to web development, I have a solid understanding of HTML and CSS, and am learning JavaScript. When considering creating a web app, would it be better for me to focus on writing the functionality in JavaScript first before integrating it int ...

Interactive section for user input

I am looking to add a commenting feature to my website that allows for dynamic editing. Essentially, I want users to be able to click on an "Edit" span next to a comment and have it transform into an editable textarea. Once the user makes their changes and ...

Is there a sweet TypeScript class constructor that can take in its own instance as an argument?

I have a scenario where I need to read in instances of Todo from a CSV file. The issue is that Papaparse does not handle dynamic conversion on dates, so I'm currently dropping the object into its own constructor to do the conversion: class Todo { ...

Getting a variable from an ajax call and using it in a Pug template

Currently, I am experimenting with Express and Pug to learn some new concepts. Upon making a request to a website, I received some dynamic information stored in an array. However, I am facing challenges when trying to iterate over this array using Pug. The ...

Experiencing the 'invalid_form_data' error while attempting to upload a file to the Slack API via the files.upload method in Angular 8

I am currently working on a project that involves collecting form data, including a file upload. I am trying to implement a feature where the uploaded file is automatically sent to a Slack channel upon submission of the form. Despite following the guidance ...

Strengthening JavaScript Security

Throughout the past few years, I have delved into various javascript libraries like Raphael.js and D3, experimenting with animations sourced from different corners of the internet for my own learning. I've obtained code snippets from Git repositories ...

In AngularJS, the $http get method is displaying the status code of the data object instead of

After pondering over this issue for several days, I am still unable to pinpoint what I am doing wrong. Any suggestions or insights would be greatly appreciated. My challenge lies in trying to showcase the response from a rest service to the user by utilizi ...

Is there a way to directly set object parameters when a web page loads using JavaScript?

Is there a way to read params values directly into NPAPi plugin? Here is the current JS and form code: <script> var control = document.getElementById('embed'); </script> <form name="formname"> <input type=button value="In ...