Avoid calling the inherited method multiple times in ES6 classes

Transitioning from RequireJS to browserify (along with babelify) has led me to rewrite my current modules as classes. Each of my RequireJS modules has a method named eventHandler that manages module-specific events. However, when extending a class, the subclass's eventHandler is called twice - once by the parent class and again by the subclass.

Parent class:

'use strict';

class Tooltip {
    constructor() {
        this.eventHandler();
    }

    eventHandler() {
        // Module specific events
    }
}

module.exports = Tooltip;

Subclass:

'use strict';

import Tooltip  from './Tooltip';

class Block extends Tooltip {
    constructor() {
        super();
        this.eventHandler();
    }

    eventHandler() {
        // Module specific events
        // Gets called twice
    }
}

module.exports = Block;

I appreciate the simplicity of having the eventHandler method consistently named across all modules for easier maintenance. Is there a recommended solution to prevent the method from being invoked twice in this scenario? Thank you for any advice!

Answer №1

If you are aware that the parent constructor is already calling this.eventHandler, then avoid doing so in the derived classes:

'use strict';

import Tooltip  from './Tooltip';

class Block extends Tooltip {
    constructor() {
        super();
        // (No call here)
    }

    eventHandler() {
        // Module specific events
        // Gets called twice
    }
}

module.exports = Block;

In response to your comment:

The parent classes may not always have an eventHandler method, so I must ensure it is actually called in those cases.

When the parent class contains the eventHandler method, refrain from making the call. However, when it does not, make sure to call it. The relationship between subclasses and superclasses is inherently close-knit.

If you can reasonably assume that the presence of eventHandler in the super means it has been invoked from its constructor, you could consider implementing something like this:

constructor() {
    super();
    if (!super.eventHandler) {
        this.eventHandler();
    }
}

Nevertheless, given the tightly-bound nature of the super/sub relationship, relying on your understanding of whether the super includes this behavior or not seems justifiable.

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 AngularJS UI-Router transition occurs without updating the URL when parameters are passed

When using UI-Router to navigate to a detailed view, I am facing an issue where the state changes correctly and parameters are passed correctly, but the URL address in the browser remains unchanged. I want to be able to display the passed params in the URL ...

Exploring the hidden gems of npm package.json: the keys

There are some keys in the package.json file of Angular 2/4's source code that remain undocumented: { "name": "@angular/platform-browser/animations", "typings": "../animations.d.ts", "main": "../bundles/platform-browser-animations.umd.js", "m ...

Could anyone clarify the concept of how a function is able to be equivalent to zero?

function checkForSpecialCharacters(text) { var specialChars = [";", "!", ".", "?", ",", "-"]; for(var i = 0; i < specialChars.length; i++) { if(text.indexOf(specialChars[i]) !== -1) { return true; } } ...

Prevent computed observables from being included in server data by using KnockoutJS

While working on this project, I came across a helpful section in that discusses "Determining if a property is a computed observable." In order to achieve this, I utilized the isComputed function to validate whether a property is indeed a computed observa ...

Use a loop to assign numbers to elements in an array based on a specific condition using JavaScript

Hello, I'm in the process of creating a looping pattern based on the conditions of the array object key. If the 'o' contains 't', the index will start from the 'n' starting point in the object, otherwise, the numbering wi ...

Triggering an AngularJS function upon window close event

Can someone help me figure out how to call an AngularJS function when a window is closing? Currently, I have the following code: app.controller("reportCtrl", function($scope, $http) { $scope.deleteReport = function() { $http.get("/SCTrakker/api/delet ...

Error message encountered while using NEXJS Stripe v3:1 library: Unhandled promise rejection IntegrationError - Stripe() requires a valid apiKey in string format

v3:1 IntenationalIssue: Stripe() is requesting a missing value - apiKey must be a string. Encountering this issue in my Next JS project while attempting to implement a pre-built checkout with stripe. .env.local (full key has been replaced with ..... for ...

What is the best way to deselect all rows from the <Table> component in Material-UI while using ReactJS?

Currently, in my ReactJS application using Material-UI's <Table/>, I have successfully implemented the select all checkbox feature. The functionality keeps track of which row has been selected by using onRowSelection={this.handleRowSelection}. H ...

Error: Attempting to insert or update the "tokens" table violates the foreign key constraint "tokens_userId_fkey" in Sequelize

I am facing an issue that I can't seem to resolve, as I keep encountering an error related to a constraint violation. The tables involved in this problem are Token and User, which are linked through the userId column. The error occurs when I try to cr ...

The shopping cart is unable to display the name property as it is undefined

I'm currently working on creating a basic shopping cart using JavaScript. $('.addToCart').click(function(event) { event.preventDefault(); var name = $(this).data('name'); var price = Number($(this).data('price')); ...

Javascript Solution for Testing Palindromes in a Linked List

I recently researched the solution for a palindrome problem using Javascript. There is one particular line of code that I am struggling to comprehend, and I'm hoping someone can shed some light on it for me. Here is the code snippet in question: thi ...

Adding up values of objects in a different array using Vue.js

Recently, I started using VueJs and encountered an object that contains arrays. One of the tasks I need to accomplish is to display the total sum of all amounts in one of the columns of the table. Here is my table structure: < ...

What is the best way to determine the accurate size of a div's content?

There are 2 blocks, and the first one has a click handler that assigns the block's scrollWidth to its width property. There is no padding or borders, but when the property is assigned, one word wraps to the next line. The issue seems to be that scrol ...

405 Error: AJAX call is not permitted

I am currently working on creating a form that will submit a JSON object to an application on a different server, but I am encountering a 405 Method Not Allowed error in the console. The application is configured to accept POST requests, which is exactly ...

Is it possible to easily remove the trailing comma, period, or other punctuation from the end when using the JavaScript pug template engine?

Apologies for the confusion in my question wording. To illustrate, here is an example piece of code: p #[strong Genre]&nbsp; each val in book.genre a(href = val.url) #{val.name} | , I am trying to figure out how to format a comma ...

Is it possible for me to ensure that the argument passed to `res.write` is sent as one solid chunk?

When utilizing express' res.write method to send chunks back to the requestor, it is important to note that one call to res.write does not necessarily mean the argument passed will be received as a single chunk. This can complicate the process of pars ...

Tips for sorting ng-Table using an array of numerous values

I am currently working on implementing angular-selectize.js (https://github.com/machineboy2045/angular-selectize) into my project. This will create a search box that allows for entering multiple values to filter all cells in an ng-Table without the need to ...

Unable to locate index.html file in Docker container while dockerizing React application

I'm a newcomer to Docker and I'm looking to containerize my react app. The index.html file is located in the public folder within my react project. However, when I try to run the docker image, it fails with an error indicating that the index.html ...

Tips for utilizing the if statement within ng-repeat in Angular version 1.0.8

My version of angular is 1.0.8-stable My main goal is to arrange data in rows of 3. This is the desired structure for my HTML: <div class="table-row"> <div class="item">item1</div> <div class="item">item2</div> ...

Tips for removing the y-axis line in ChartJs

How can I hide the y axis line in a bubble chart? I attempted to use the code snippet below but it did not work as expected. yAxes: [{ angleLines: { display: false } }] ...