Call upon the prototype method of the parent class

"I'm having trouble understanding a piece of my code:

       //constructor
       function Widget (options) {            
        };

       //return the string
        Widget.prototype._addEditFormString = function (val) {
            return "<input type='text' value='" + val + "' >";                
        } 
        //initializing method
        Widget.prototype.init = function () {
            var addRowButton = document.getElementsByName("addRow")[0];              
            addRowButton.addEventListener("click", this.addRow, false);                
        };
        //this context in this method is still confusing me
        Widget.prototype.addRow = function () {    
            console.log(this._addEditFormString);//Uncaught TypeError: Object #<HTMLInputElement> has no method '_addEditFormString'                  
        }  
        var wid = new Widget();

         wid.init();

The issue - In the init() method I add an event listener (addRow method), but in the addRow method, I am unsure how to reference "this" of my constructor class. I want to invoke _addEditFormString() method, but I receive "Uncaught TypeError: Object [object Window] has no method '_addEditFormString'". How can I solve this without using Widget.prototype._addEditFormString? Is that the only solution? Thank you.

Answer №1

The issue lies in the context of the event handler being set to the window rather than your Widget.

Modify

Widget.prototype.init = function () {
     var addRowButton = document.getElementsByName("addRow")[0];              
     addRowButton.addEventListener("click", this.addRow, false);                
};

to

Widget.prototype.init = function () {
      var _this = this;
      var addRowButton = document.getElementsByName("addRow")[0];              
      addRowButton.addEventListener("click", function(){_this.addRow()}, false);                
};

Edit related to your query in the comment :

You appear to be looking for

Widget.prototype._addEditFormString.call(this);

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 it possible to combine ng-switch and ng-if directives in Angular?

I attempted to combine the angular ng-switch and ng-if directives, but it doesn't seem to be functioning properly. Here is what I tried: <div data-ng-if = "x === 'someValue'" data-ng-switch on = "booleanValue"> <div data-ng-swit ...

Experimenting with an Angular Controller that invokes a service and receives a promise as a

I am currently in the process of testing an angular controller that relies on a service with a method that returns a promise. I have created a jasmine spy object to simulate the service and its promise-returning method. However, my mock promise is not retu ...

Is it possible to create two header columns for the same column within a Material UI table design?

In my Material UI table, I am looking to create a unique header setup. The last column's header will actually share the same space as the previous one. Picture it like this: there are 4 headers displayed at the top, but only 3 distinct columns undern ...

What steps should be taken to generate a successful pop-up window post registration in PHP?

beginning section continuation What is the best way to design an effective popup window? ...

Pressing a button meant to transfer text from a textarea results in the typed content failing to show up

Having trouble with a custom text area called a math field. I'm currently interning on a project to build a math search engine, where users can input plain text and LaTeX equations into a query bar. The issue I'm facing is that sometimes when th ...

What are the best practices for iterating through asynchronous generator functions?

Suppose we have an asynchronous generator: exports.asyncGen = async function* (items) { for (const item of items) { const result = await someAsyncFunc(item) yield result; } } Can we apply mapping to this generator? In essence, I am attempting ...

retrieveSourceData(), postmodification of Handsontable with Vue

How can I use getSourceData() after a change event in Vue? I need to access the instance of Handsontable, but I'm not sure how to do that in Vue. Essentially, I need to retrieve all rows that have been edited. For example: const my_instance = this.$ ...

Struggling to create an access token with the Slack API

My goal is to retrieve an access token from the Slack API. When I use the code provided below, it generates an authorization URL containing a temporary code in the query string. Once permissions are granted, the process redirects to /slack/oauthcallback. ...

Is there a way to retrieve the HTML code of a DOM element created through JavaScript?

I am currently using java script to generate an svg object within my html document. The code looks something like this: mySvg = document.createElementNS("http://www.w3.org/2000/svg", "svg"); myPath = document.createElementNS("http://www.w3.org/2000/svg", ...

Tips for validating a string in a URL with Selenium IDE

When I click on a tab on my website, it triggers an AJAX service call where the URL contains parameters related to the data being loaded after the tab is clicked. The data is displayed as horizontal tiles one below the other, with 4 tiles being loaded pe ...

Tips for adjusting the property of an object that has been added to an array?

I have created an object. { "heading": [{ "sections": [] }] } var obj = jQuery.parseJSON('{"header":[{"items":[]}]}'); Then I add elements to the sections var align = jQuery.parseJSON('{"align":""}'); obj["he ...

Setting up a retrieval callback in mongoose and storing it in a global variable

Is there a way to set the value of db as a global variable? I am having trouble with getting the console output of name outside of the findOne function, it keeps showing me undefined. Any suggestions on how to fix this issue? var name; schema.findone({na ...

Refreshing AJAX content with a dynamically adjusting time interval

I am facing a scenario where I have a webpage featuring a countdown alongside some dynamic data refreshed via AJAX. To optimize server load, I found a clever solution by adjusting the AJAX refresh interval based on the time remaining in the countdown, foll ...

Substitute all attributes of objects with a different designation

I need to update all object properties from label to text. Given: [ { "value": "45a8", "label": "45A8", "children": [ { "value": "45a8.ba08", "label": "BA08", &q ...

Tactics for postponing a js function post-click

I need to implement a delay after clicking a button to fetch some data. The code will be executed within the browser console. $(pages()) is used to retrieve the pagination buttons. let calls = []; for (let i = 1; i <= callPagesCount; i++) { ...

Throttle the RxJs interval based on the inner observables

Sorry if the way I am asking this question is not clear, I am having difficulty finding the right words to explain it. I am currently working on Selenium automation and here is how the process goes:- Go to a specific page Every 1 second, check if the pag ...

Issues with the Content Editable Functionality

While working on my website, I encountered a strange issue. For some reason, I can't seem to get the contenteditable="true" attribute to work on the heading with the ID "hl". It would be awesome if someone could help me figure out how to mak ...

Having trouble sending data from AJAX to PHP

My goal is to implement a "load more" feature in my web app that automatically calls a PHP file to load additional products as soon as the page is fully loaded. In order to achieve this, I am using AJAX to call the PHP file: $(document).ready(function() { ...

Deleting occurrences of a specific text from a JSON document and subsequently analyzing its contents

I am having an issue with a JSON file in which there are strings of characters attached to many of the field names. This is making it difficult for me to target those objects in JS. The structure looks like this: "bk:ParentField": { "bk:Field": "Va ...

Is there a way to prevent SignalR from disconnecting when the settings window is moved?

I am currently developing a webpage that utilizes SignalR events to trigger ajax requests to our servers. These requests return a URL with a custom URI scheme that, when accessed, opens up a specific program on the client's device without leaving the ...