Replace the function if it is specified in the object, otherwise use the default functionality

Having a calendar widget written in TypeScript, I am able to bind a listener to a separate function. However, I desire this separate function to have default functionality until someone overrides it in the config object passed to the constructor. Within the constructor, I pass something similar:

{
  container: 'xxx',
  cellClick: function(sender, event, data) {
    // custom functionality
  }
}

How can I define a function cellClick in my base class and when rendering my td cells, bind an event listener to this function and pass some data for the cell which will have default functionality initially, but allow for override if the function is defined in the object for the clicked cell.

I attempted something like that, but it binds the listener directly to the config function. I believe it could be easily achieved within my setter, but I cannot figure out how.

td.addEventListener('click', function () {
  this.config.cellClick(td, event, data);
})

EDIT: Here's my abstract class which extends the Table class responsible for creating objects for thead, tbody, and tfoot:

// Abstract class code here...

Furthermore, there is a class Calendar extending the abstract class and serving as the main class instanced with the configuration object.

// Calendar class code here...

There are 3 additional classes for the view render and logic handling, all working with the table object to perform various operations.

Lastly, here is how I initialize it:

// Initialization code here...

Since I'm not very experienced with OOP, any suggestions for refactoring would be greatly appreciated.

Answer №1

One way to set default functions is by providing a default object:

defaultFuncs = {
    option1: 'value1',
    cellHover: function() {/*default hover action*/}
}

To merge your configuration object with the default object, you can use Object.assign:

Object.assign(defaultFuncs, config || {});

Your defaultFuncs object will now contain all default values unless overridden by values in the config object. You can then use

td.addEventListener('mouseover', defaultFuncs.cellHover)

This will attach either the default function or an overwritten function as the event handler.

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 return true to asp.net OnClientClick following an Ajax request? Alternatively, is there another method that can be used?

I am currently implementing an Ajax call to verify if a user is logged in. If the user is not logged in, I want to display a login dialog; otherwise, I need OnClientClick to return true so that the form can be submitted. I am considering using a global var ...

Learn how to toggle the menu list visibility by clicking on a component in Vue

I seem to be having an issue with closing a menu item in vue and vuetify2. Here is the code snippet that I have: <v-menu transition="slide-y-transition" bottom left offset-y nudge-bot ...

What is the best way to determine the height of a DIV element set to "auto"?

When setting a fixed height on a div using jQuery, such as $('div').height(200);, the value of $('div').height() will always be 200. This remains true even if the content within the div exceeds that height and overflow is hidden. Is th ...

The array is present both before and after the res.json() call, however it appears empty in the response

When using Express to send a json response with res.json(), I am experiencing an issue where the value of records in the object sent via res.json() is empty. My code snippet looks like this: stats.activities(params).then(res => { processActivities ...

Can someone explain the distinction between 'return item' and 'return true' when it comes to JavaScript array methods?

Forgive me for any errors in my query, as I am not very experienced in asking questions. I have encountered the following two scenarios :- const comment = comments.find(function (comment) { if (comment.id === 823423) { return t ...

The login form is experiencing issues with submission when utilizing the submitFormHandler in ReactJS

In my single-page application, I'm working on creating a separate login page that will redirect the authenticated user to the main application. However, I'm encountering an issue where my submitFormHandler is not being invoked. The purpose of aut ...

Is Fullpage.js functioning only on local servers?

I have decided to create a personal website showcasing my portfolio using the fullpage.js library. Everything seems to be working fine during development, but once I upload the site to my github.io or another public domain via FTP, I encounter GET errors t ...

The React forwardRef Higher Order Component is failing to provide a reference to the container element

I'm currently working on creating a higher order component (HOC) for closing an element when clicked outside of its space, known as a generic close on outside solution. In my understanding, this can be achieved using forwardRef and HOC implementation ...

Issue with Angular: Child component not receiving data after successful parent component call

I'm currently working with a parent and child component setup. Within the child component, I have a button configured like this: //child.component.html <button mat-raised-button [disabled]="!form.valid || submitButtonDisable" type = 'Submi ...

Enhance user experience with AngularJS Bootstrap autocomplete feature by automatically filling input box when hovering over dropdown options

I am currently implementing the AngularJs Bootstrap typeahead functionality. Typically, when we enter text that matches an option, the dropdown list appears. https://i.stack.imgur.com/395Ec.png What I aim for is to automatically fill the textbox with the ...

Tips for adding an svg element to an existing svg using d3.js

Can another SVG be appended to an existing SVG parent using d3.js? I have tried using the 'svg:image' attribute, but unfortunately, I lose full control over the inner SVG child. The DOM node is created by d3, but it is not rendered, resulting i ...

Top method for organizing an array based on an object's property and displaying the outcome

I encountered a problem for which I couldn't find an immediate solution. I have an array of objects representing products, with each product having a category property. My goal is to group these products by their categories. After some trial and error ...

Is there a specific type of function missing in Typescript?

I am facing a challenge in converting an existing JavaScript code to Typescript. The original javascript code is as follows: object.getsomething( function(err, result) { // async }); I am confused about how to properly type the parameter "function(er ...

Tips for positioning a div relative to another div while controlling its z-index

Hey there, take a look at the image below https://i.sstatic.net/zYiaY.png The issue I'm facing is quite common - I have div 1 and div 2 visible in a loop, but divs 3 are hidden. When div 2 is clicked on, everything is great so far. However, what I wa ...

Stopping Angular.js $http requests within a bind() event

As stated in this GitHub issue Is it expected to work like this? el.bind('keyup', function() { var canceler = $q.defer(); $http.post('/api', data, {timeout: canceler.promise}).success(success); canceler.resolve(); } ...

ng-show and ng-hide toggling for the active row

I have a single table where I am implementing row hide and show functionality using Angular for editing and saving purposes. So far, everything works as expected. $scope.init=function(){ $scope.editable=true; } Now, when I click on the edit button ...

Consolidating multiple inputs into a single saved value

How can I combine three input values into one input field using onchange event in JavaScript? <script type="text/javascript"> function updateInput($i){ $('updateval').val($i); } </script> <input type="text" onchange="updat ...

Utilize JSX to dynamically insert HTML tags onto a webpage

I am trying to achieve a specific task in JSX, where I want to identify all strings enclosed within delimiters :; and wrap them with HTML Mark tags to highlight them. However, the current implementation is not rendering the tags as expected. Is there a sol ...

Having trouble getting unique input values to pass through ajax

For the past couple of weeks, I've been searching for a solution to my issue. The problem arises in my PHP foreach loop where I have div tags representing rows of data fetched from the database. Each div row contains HTML input elements and a button t ...

When a client sends a GET request to the server, an error occurs due to the absence of 'Access-Control-Allow-Origin' header in

I am encountering an issue with my node/express js application running on localhost while making a 'GET' request to Instagram's api. The error message I keep receiving is: XMLHttpRequest cannot load https://api.instagram.com/oauth/authorize ...