Object literals that can be reused

Having a component with a table that contains action buttons, clicking on these buttons triggers the emission of various actions (such as edit, delete, route).

getEvent(action: ActionButtons, object: any) {
    // type: (edit,delete,route), route: info where to redirect
    const {type, route} = action;
    this.action.emit({ type, route, body: object });
}

In the parent component, I handle these emitted objects using the following function and execute different logic based on the action:

getAction({type, route, body: {...faculty }}) {
    const action = {
        edit: () => {
            this.openFacultyModal(faculty);
        },
        delete: () => {
            this.openConfirmDialog(faculty);
        },
        route: () => {
            this.redirecTo(faculty.faculty_id);
        }
    };
    action[type]();
}

The issue arises when wanting to reuse the table in another component, requiring cut-and-pasting of getAction() and just updating the inner functions.

This leads to code duplication.

Is there a way to address this problem of duplication by utilizing closures or creating a separate class?

Answer №1

If you want to create a reusable action map object, you can follow this approach:

const actions = {
  edit(target, faculty) {
    target.openFacultyModal(faculty);
  },
  delete(target, faculty) {
    target.openConfirmDialog(faculty);
  },
  route(target, faculty) {
    target.redirecTo(faculty.faculty_id);
  }
};

You can then utilize this object whenever needed, like in the getAction function:

getAction({type, route, body: {...faculty }}) {
  actions[type](this, faculty);
}

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

Unveiling the Power of Ionic and React for Component Repetition

I'm having trouble figuring out how to repeat my component multiple times using react in Ionic. Can someone assist me with this? Here's an example: In my Component.tsx file, I have the following code: import React from 'react'; import ...

``There seems to be an issue with implementing the SlideDown feature in JavaScript

I am having an issue with a code where the expected behavior is to slide down a div when a person hovers over text, but it's not working. Can someone please review and identify the cause of this problem? <script type="text/javascript" src="/js/jqu ...

Tips for concealing text adjustments during window resizing in an HTML document

I'm currently working with a website code that involves two sidenavs, one on the right and another on the left. When one sidebar opens, the other collapses. However, I've noticed that the text in between readjusts when the sidebars are toggled op ...

What is the reason behind Bootstrap 5's decision to have the getOrCreateInstance() method automatically toggle the collapsible element upon creation?

Today was my first encounter with the Collapse feature in Bootstrap 5, and I have to admit, I am not a fan! Imagine a scenario where I have a collapsible element that is initially hidden, and a button to toggle its visibility, like so: <button class=&q ...

Data tables failing to display accurate data

I have implemented Datatable for a table with eight identical columns and three columns that vary based on the selected radio button. The table is dynamically filled using an ajax call to a python function and the returned data is added to the table body. ...

Could someone clarify why EventEmitter leads to issues with global variables?

I recently encountered an error that took me some time to troubleshoot. Initially, I decided to create a subclass of EventEmitter In the file Client.js var bindToProcess = function(func) { if (func && process.domain) { return process.domai ...

Tips for setting up chrome-app typings in Typescript 2

I am looking to eliminate the typings in our Typescript project. After successfully removing most typings dependencies with Typescript 2, I'm left with just one for chrome-app: https://github.com/uProxy/uproxy/compare/master...fortuna:master When usi ...

Numerous asynchronous requests

I'm trying to figure out why the application keeps making multiple ajax calls. Check out this directive: gameApp.directive('mapActivity', function() { return { restrict: 'A', link: function(scope, element, att ...

When a user deletes a Web Page element from their Browser, is there an event that is triggered?

One method I have used to bypass restrictions on poorly written websites is manually deleting webpage HTML elements. To maintain security and keep intruders at bay without disrupting user experience, I am exploring options to implement automatic logout aft ...

The useState variable's set method fails to properly update the state variable

I am currently developing an application with a chat feature. Whenever a new chat comes in from a user, the store updates an array containing all the chats. This array is then passed down to a child component as a prop. The child component runs a useEffect ...

Getting rid of mysterious Google Analytics script from WordPress

My client has requested that I incorporate Google Analytics into her website. After accessing her Google account, I attempted to paste the tracking code into the appropriate section of the Wordpress plugin. To my surprise, the code did not work as expect ...

There seems to be an issue with Bookshelfjs and bcrypt hashPassword - it is functioning properly during the create

When using bcrypt to hash passwords in bookshelfjs, I encountered an issue where the password was not being hashed when attempting to update it. Here is the code snippet: model.js var Bookshelf = require('../../db').bookshelf; var bcrypt = requ ...

Tips for displaying the node's label in Arbor js when hovering over the node

I'm currently utilizing Arbor Javascript to exhibit a graph composed of nodes and edges. My objective is to have the node's label displayed when the mouse hovers over it within the graph. Below is the code snippet I am working with: <canvas i ...

"Transferring a variable from the parent Layout component to its children components in Next

I am trying to figure out how to effectively pass the variable 'country' from the Layout component to its children without using state management. Basically, I want to drill it down. import { useState, useEffect } from 'react' import La ...

Implementing json value extraction in javascript

Hello there! I'm currently having trouble constructing a JSON format. Here is the JSON response: { "txs": { "lock_time": 0, "ver": 1, "size": 372, "inputs": [ { &qu ...

Guide to transferring a JavaScript/Ajax variable to a PHP webpage with the help of AJAX

function initiateIperfSpeedRequest(speedVar, actualIp) { var xmlhttp = getAjaxObject(); xmlhttp.onreadystatechange = function () { if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { handleIperfResponse(xmlhttp.respo ...

Example using three.js showing issues with external resources failing to load on jsfiddle.net

Currently, I am endeavoring to make progress with this sample project: github.com/josdirksen/learning-threejs/blob/master/chapter-09/07-first-person-camera.html I have made attempts at replicating the code on my personal pages.github.io account and also m ...

sorting alpha-numeric values with the help of jQuery

I am looking to sort a mixed array by alphabet and then by digit [Ab-1,Ab-5,Ab-11,ab-101,ab-100,ab-10,ab-12,ab-3,ab-21] Currently, the output is: ab-1 ab-5 ab-11 ab-101 ab-100 ab-10 ab-12 ab-3 ab-21 However, I would like it to be sorted as follows: ab ...

Create a function that recursively maps data across multiple levels

Currently, I have a data mapping function that can take JSON data with up to four levels and transform it into a different format. The input JSON format looks like this: [{ "InventoryLevel2Id": "1234", "InventoryLevel2Information": "Test Data", ...

Include chosen select option in Jquery form submission

Facing some challenges with a section of my code. Essentially, new elements are dynamically added to the page using .html() and ajax response. You can see an example of the added elements in the code. Since the elements were inserted into the page using . ...