Connect 'this' to an imported function using pure JavaScript

function EmployeeListView() {
this._html = html;
/../
}

EmployeeListView.prototype = {
    registerEmployeeHandler: function (handler) {
        syncEmployeeList().bind(this);
        
}

function syncEmployeeList() {
    let elList = this._mHtml.querySelector('#employee');
    if (elList)
        elList.addEventListener('change', function () {
            var employee = document.getElementById("employee").value;
            document.querySelectorAll("input[type='text']")[0].value = "";
            handler(employee);
        });
}

i need help in binding 'this' to syncEmployeeList so that I can avoid passing it as a parameter to the functions, I am unsure of what I am doing wrong

Answer №1

It seems like you may not need to bind the function to anything. You can directly make it a method like this:

/* file A */
export function addList(handler) {
    let elList = this._mHtml.querySelector('#todo');
    if (elList)
        elList.addEventListener('change', function () {
            var todo = document.getElementById("todo").value;
            document.querySelectorAll("input[type='text']")[0].value = "";
            handler(todo);
        });
}
/* file B */
import { addList } from '…';

…
PersonListView.prototype = {
    addPersonHandler: addList,
};

(Although, it's not recommended to spread the methods of a single class across multiple files)

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

Utilizing Bootstrap Modal to trigger an Action Result function when a button is clicked

I could use some assistance. In my current setup, I have a file picker that loads a file into a specific table in my database. When the user clicks a button, a bootstrap modal pops up to ask if they are uploading more files. This is how it looks in my vi ...

Having trouble with the npm package installation for react-circular-progressbar

I encountered an error when trying to install react-circular-progressbar in my React projects. Why is this happening? npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency tree npm ERR! npm ERR! While resolving: <a href="/cdn-cgi/l/em ...

Using JQuery to Execute Matching Based on Text Within <A> Elements

After reviewing the resources on Jquery Extract URL from Text and jquery match() variable interpolation - complex regexes, I am still a bit confused. The issue at hand is that I have a webpage with a dropdown menu at the top. Inside the dropdown, there ...

Using JavaScript to parse Java objects into JSON data

I'm working on sending an array of POJOs as a response to an AJAX call. Within my POJO, the following toString() method is defined: @Override public String toString() { return "Expense [period=" + period + ", description=" + description + ...

"Aligning the title of a table at the center using React material

I have integrated material-table into my react project and am facing an issue with centering the table title. Here is a live example on codesandbox: https://codesandbox.io/s/silly-hermann-6mfg4?file=/src/App.js I specifically want to center the title "A ...

Is it possible to have a div automatically scroll when hovered over, while also hiding the scroll bar specifically for that div?

Is there a way to autoscroll a specific element onmouseover or via an image map while also hiding the scrollbars for that div? I seem to be struggling with this task despite weeks of learning javascript and not being able to find the right solution online. ...

Unable to fetch the Observable value

I have a function that returns an Observable<Person[]>, where Person is my model: export interface Person { id: string; age: number; } Now in my component.ts, I am calling this function and aiming to retrieve the array to display it in the HTML ...

Deliver a message using a loop in jade

I'm struggling with posting a request in Node and Jade using a specific ID. For instance, if Node returns a list of books : res.render('tests', {books: books}); In my Jade template, I display all the books by iterating through them. b ...

delete the final directory from a file directory

let currentLocation = window.location.pathname; let directory = currentLocation.substring(0, currentLocation.lastIndexOf('/')); The current location is: /examples/html/home/ The directory is: /examples/html/home I am trying to remove the las ...

Can we determine if a user's operating system has disabled animations?

In my frontend project with React, I am incorporating an animation within a component. However, I want to cater to users who have disabled animations in their settings by replacing the animated content with a static image. Is there a method to detect if ...

Discovering Angular 2 Service Change Detection

Exploring the Angular 2 beta has led me to some challenges with understanding the change detection mechanism. I have put together a simple Plunker example that demonstrates an issue I am encountering. //our root app component import {Component, Injectab ...

Array specifically designed for replacing strings, but it only works with the final element

Here is a snippet of code I am working with: $(document).on('click','.submitMessage,.submitStdMessage', function(e){ prevContent=$('textarea').val(); alert(prevContent); variables = { '{nom}' ...

Tips for updating a reactive form with multiple layers of nested JSON values

I am tasked with retrieving and working with the data from a deeply nested (potentially infinite levels) reactive form that includes formArrays, formGroups, and formControls. This data is stored in a database. Currently, my approach involves patching the ...

Using a JQuery for loop to update the value of an input field based on the selected option's attribute, with only the last value

I need to simplify this lengthy code snippet, which is currently functioning well: $(document).ready(function() { $("#PayRate1").change(function() { $('#HourlyRate1').val($('option:selected', this).data('rate')); ...

Is it possible to prevent a webpage from being refreshed?

I need help with an HTML page that puts the worker on pause time which will be subtracted from his/her day job. The issue is that when he/she refreshes the page, the timer starts from the beginning automatically. I want it to continue without resetting. Is ...

Update the image links to automatically refresh every half a second based on the values inputted in the text bars

Is there a better and simpler way to define AAAAAAAAAA, BBBBBBBBBB, and CCCCCCCCCC using the links provided in the text bars named chart1, chart2, and chart3? This learning project is being done through Notepad++ for personal use only, with no need to sa ...

Creating a primary php file in Apache without the use of SQL or any database: is it possible?

Forgive me if this comes across as rude, but I'm struggling to grasp the concept of apache, PHP, and servers in general. To help myself understand better, I want to create a very basic website that assigns an ephemeral ID to each user (not a session). ...

Unexpected quirks noticed in the .html() function with jQuery and JavaScript

I have this straightforward HTML code: <td id="comment_td"> </td>. Notice the two spaces inside the td tags. I am checking the content of the td element like this: if (!$('#comment_td').html()) { $('#comment_td').html( ...

Having trouble with Jest and React IntersectionObserver mock not functioning properly?

While working on my component.test.js file, I attempted to mock the IntersectionObserver using the following code: const mock = ()=>({ observe: jest.fn(), disconnect: jest.fn() }); window.IntersectionObserver = jest.fn().mockImplementation(mock) ...

What is preventing me from updating one dropdown list based on the selection made in another dropdown list?

I have a situation on a classic asp page where there are two dropdown lists: <select id="ddlState" name="ddlState" runat="server"> <option value="KY">Kentucky</option> <option value="IN" ...