Creating a JavaScript functional 'class' to easily access a method both from within and outside the function

I have developed a function that manages various tasks related to paginating and sorting a table. This function includes a key method that executes the database query and updates the display table.

I aim to access this inner function/method from within the function itself, as well as externally through the object that was created.

handleFunction = function() {
    mainMethod = function() {
        console.log('you found me');
    };

    document.getElementById('test').addEventListener('click', function (e) {
        mainMethod();
    });

    mainMethod();
};

myHandler = new handleFunction();
myHandler.mainMethod();


handleFunction = function() {
    this.mainMethod = function() {
        console.log('you found me');
    };

    document.getElementById('test').addEventListener('click', function (e) {
        // would need to use bind here, which can complicate things
        mainMethod();
    });

    this.mainMethod();
};

myHandler= new DrawShape();
myHandler.mainMethod();

The first approach allows global accessibility of the mainMethod function within handleFunction, but it cannot be called from outside.

The second approach enables calling myTest.mainMethod externally, but using it within an inner function requires binding, causing complications in maintaining target accuracy.

Is there a more efficient solution?

Answer №1

To enhance the function as a callback, you have the option to switch it with an arrow function or to utilize bind prior to executing the function as previously suggested.

testFunction = function() {
    this.keyMethod = function() {
        console.log('ya got me');
    };

    // Instead of using 'callback', directly provide the function for invocation.
    // This is suitable if there's no usage of the `this` keyword within the function.
    document.getElementById('test').addEventListener('click', this.keyMethod);

    // In case your callback involves the use of the `this` keyword, consider either using an
    // arrow function or binding the function beforehand.
    document.getElementById('test').addEventListener('click', event => this.keyMethod());
    document.getElementById('test').addEventListener('click', this.keyMethod.bind(this));

    this.keyMethod();
};

console.log("constructor output:");
myTest = new testFunction();
console.log(".keyMethod() output:");
myTest.keyMethod();
console.log("click event output:");
<button id="test">test</button>

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

Enhancing React's state management using Immutable principles

I'm currently facing issues trying to update my React state using Immutable. The state is not deeply nested or derived from anything other than itself, for example: { "username" : "keyval" : null}} Due to this structure, I am unable to simply use use ...

`The Issue with Ineffective Slider Removal`

Below is the complete code: import React, { Component } from "react"; import "./App.css"; import Slider from "@material-ui/core/Slider"; import Typography from "@material-ui/core/Typography"; class App extends Compo ...

Can React tooltips have properties that allow for changing text styles, such as making text bold or unbold?

Seeking assistance on how to change bold text to regular text in react-tooltip. I have already installed npm react-tooltip. Note: The default text appears in bold and I would like it to be normal. ...

A guide to performing a LEFT JOIN on two JSON data sources from external URLs

I've been attempting to achieve the following outcome using external JSON data but haven't had any luck finding a solution on search engines or forums. Can anyone provide assistance with this? Thank you in advance. people = [{id: 1, name: "Tom" ...

Show various error messages depending on the type of error detected

When pulling data from an API, my goal is to handle errors appropriately by displaying custom error messages based on the type of error that occurs. If the response is not okay, I want to throw an error and show its message. However, if there is a network ...

While creating a customer profile sample, I encountered an issue where I received an error message stating "POST http://localhost:3000/cusprofiles/add 400 (Bad Request)" when attempting to add data

I'm having trouble creating a customer profile for a vet clinic in my code. I'm unable to add and edit customer details, and I'm not sure where I've made a mistake. The only method that seems to be working is the GET method. Can someone ...

Learn how to automatically update data in Vue JS after making a 'POST,' 'DELETE,' or 'PUT' request in Vue JS 2

Whenever I send a 'POST' or 'DELETE' request, the data doesn't update automatically. I have to manually reload the page to see the updated information. Is there an easy way to refresh the data after making any 'POST' / &a ...

Is WebStorm with Node Supervisor being utilized to eliminate the need for restarting after every code modification?

Currently, I am utilizing WebStorm as my node IDE and have found it to be quite impressive. However, one issue I am facing is figuring out how to incorporate node supervisor into my workflow within WebStorm. Has anyone successfully managed to set this up ...

The issue of resolving NestJs ParseEnumPipe

I'm currently using the NestJs framework (which I absolutely adore) and I need to validate incoming data against an Enum in Typscript. Here's what I have: enum ProductAction { PURCHASE = 'PURCHASE', } @Patch('products/:uuid&apos ...

Retrieve and modify the various elements belonging to a specific category

I'm currently developing a chrome extension and I need to access all elements of this specific type: https://i.stack.imgur.com/sDZSI.png I attempted the following but was unable to modify the CSS properties of these elements: const nodeList = documen ...

Navigate through the DOM to return an image

I have a question about clicking on the image '.escape' and passing back the source of the image '.myimg2' when clicked. Here is my attempt at accomplishing this task: I understand that it involves traversing the DOM, but I am not very ...

Steps to combine multiple arrays into a unified array:1. Begin by allocating a

To form a league table, I have multiple individual arrays filled with data. In order to sort them by points, I want to merge these arrays into a single array called "teams". However, I am unsure if there is a function available to achieve this specific f ...

Infinite loop caused by Angular JS routing止

I have set up a Django server with the following configuration: urls.py urlpatterns = [ url('^', IndexView.as_view(), name='index') ] landing/urls.py urlpatterns = [ url(r'^admin/', admin.site.urls), url('^.*&a ...

What sets apart a Functor from the Command pattern?

While I have a solid grasp on the Command pattern, I'm still struggling to differentiate between a Functor and a command in theory. Specifically within Java implementations. Both serve as programming "verbs" implemented as objects. However, functors o ...

Using a different method to handle multiple callbacks in Angular or a suitable replacement for $.Callbacks

Is there a similar functionality in Angular to jQuery $.Callbacks? I am seeking a straightforward method to manage callback lists within Angular. My goal is to achieve the following using Angular: function Broadcast(){ var self= this; this._status ...

HTML5 for advanced positioning and layering of multiple canvases

I have 2 canvas layers stacked atop each other, but I need to position them relative to the entire page. The dimensions of both layers are fixed at a width of 800 and a height of 300. My goal is to center the canvas layers regardless of screen size, with ...

HowlerJS: Unauthorized Access - Error Code 401

Working with Angular 7, I have developed an application that consumes data from an API. I have successfully implemented CRUD functionalities using an http-interceptor that adds a token to each request. However, I encountered a 401 error when integrating Ho ...

What is the best way to remove data from both arrays simultaneously?

I am working with a grid that displays a list of time ranges. For example: timeList=[{from:12:00:00 , to:14:00:00 ,id:10}{from:08:00:00 , to:09:00:00 ,id:11{from:05:00:00 , to:10:00:00 ,id:12}}] time=[{Value:12:00:00 id:10} {Value:14:00:00 id:100} ...

The content located at “http://localhost:3000/public/static/” was restricted because of a mismatch in MIME type (text/html) which triggered the X-Content-Type-Options:nosniff protocol

https://i.stack.imgur.com/7Etn7.png Every time I try to run the server with nodemon, I keep encountering the error mentioned in the title. Below is the code snippet from the JavaScript file: const express = require('express') const path = requir ...

Updating the dimensions of a Shape in ThreeJS

Is it possible to update the dimensions of a Shape in ThreeJS without the need to recreate the entire shape each time? I am creating a square based on the user's mouse movement to define the area of zoom. Currently, I recreate the square shape and ad ...