Is it possible to combine 2 methods into 1 method in Vue and include optional parameters?

There is a method that handles enabling a single notification, emitted from a child component:

handleOne(name, enabled) {
  if (!this.hasPerms()) {
    return;
  }
  if (!!this.loggedInUser) {
    this.toggleNotif({
      notifName: name,
      newAnalytics: {
        type: 'brand',
        true,
      },
    });
  } else {
    login.redir('new');
  }
},

A new method was created to handle enabling all notifications, which internally requires separate actions (toggleNotif and toggleAllNotif):

handleAll() {
  if (!this.hasPerms()) {
    return;
  }
  if (!!this.loggedInUser) {
    this.toggleAllNotif({
      newAnalytics: {
        type: 'allBrand',
        true,
      },
    });
  } else {
    login.redir('new');
  }
},

The two methods are somewhat similar but differ in arguments and internal method calls. The question is whether it would be better to refactor the handler into one method with conditional parameters or if that would overcomplicate things:

handleAll(turnOnAll=false, name=false, enabled=false) {
  if (!this.hasPerms()) {
    return;
  }
  if (!!this.loggedInUser) {
    if (turnOnAll) {
      this.toggleAllNotif({
        newAnalytics: {
          type: 'allBrand',
          true,
        },
      });
    } else { 
      this.toggleNotif({
        notifName: name,
        newAnalytics: {
          type: 'brand',
          true,
        },
      });
    } 
  } else {
    login.redir('new');
  }
},

Answer №1

Implement a function that handles different cases based on arguments passed. Only the name, toggleNotif, and type change, so utilize arguments to manage these scenarios:

handleAction(action, type, name) {
   if (!this.hasPermissions()) {
      return;
   }
   if (!!this.currentUser) {
      this[action]({
         notificationName: name,
         newType: {
            type,
            true,
         },
      });
   } else {
      login.redirect('new');
   }
},

To invoke, for instance, use

handleAction('toggleNotif', 'brand', someName)
or
handleAction('toggleAllNotif', 'allBrand')
.

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

Guide to sending a specialized SPL token using the libraries '@solana/web3.js' and '@solana/sol-wallet-adapter'

Attempting to transfer a custom SPL token using the solana-wallet adapter is proving to be challenging due to difficulty in obtaining the wallet's secret key for signing the transaction. Although I have reviewed resources on writing the transfer code ...

Using jQuery to Retrieve an Element's Class Through an AJAX Call

For my website, I am using ajax to load pages by replacing the content in the main tag. The issue arises when working with Wordpress, as each page has its own set of body classes for styling purposes. My goal is to replace the old page's body classes ...

Customizing Bootstrap styles when toggling

I have been working on incorporating a dark/light theme into my project. By creating a separate SCSS file that is imported after the main Bootstrap file, I was able to override certain core Bootstrap styles to achieve a dark/light mode. Now, I am facing th ...

How to Make WebService Calls in JavaScript in ASP.NET without ScriptManager

I developed a Web service for my Asp.net project. Right now, I am accessing the service through JavaScript by including the Service in ScriptManager. However, I am looking to eliminate the need for a ScriptManager so that I can utilize it on any HTML pag ...

What steps should I take to ensure axios is returning the appropriate buffer type?

Upon initially posting this question, I was completely lost on where to even begin or how to appropriately title it. With the assistance of multiple comments, I enhanced the data provided and finally settled on the current question title - a big thank you ...

`Angular RxJS vs Vue Reactivity: Best practices for managing UI updates that rely on timers`

How can you implement a loading spinner following an HTTP request, or any asynchronous operation that occurs over time, using the specified logic? Wait for X seconds (100ms) and display nothing. If the data arrives within X seconds (100ms), display i ...

Error: Unable to transform org.w3c.dom.domElement into a boolean value

After translating the Javascript code to Java, I came across an issue within the sib; portion. More information can be found at: I am unfamiliar with such for statements. What is the function of adding a semicolon? Does it behave like a while() statement? ...

Retrieve the .js file from a WordPress plugin

I need assistance with loading a .js file from a WordPress plugin. Within the main plugin file, I have code that loads jQuery, jQuery-UI, and my .js file: //Load Java and Jquery function load_jquery() { // only use this method if we're not in wp ...

Tips for showcasing embedded content in WordPress without the need for scrolling

I am in the process of building a website. The sidebar menu contains a list of pages and posts from my WordPress blog. Whenever I select a menu item, the content is displayed within one of the templates I have created in an Iframe. However, there seems to ...

Tips for displaying or concealing table rows with form fields on a php site by utilizing jquery/ajax and a drop-down menu selection

Is there a way to hide or unhide table rows with form fields in a php website based on a dropdown selection using jquery/ajax? The current script I have only hides the field, leaving blank rows. How can I also hide the respective table rows? Thank you for ...

Tips for sending values via props to a different component and the common error message: "Consider using the defaultValue or value props instead of setting selected on the <option> element"

Currently, I am attempting to pass the selected value using the prop: handle state change, but encountering two errors. Error 1 : Instead of setting selected on <option>, use the defaultValue or value props. Error 2 : A property 'active' ...

Tips for retrieving the ID of a newly added Firestore document in Vue.js

I am currently using Vue.js and Firebase to create a very basic CRUD functionality. One issue I have encountered is that when I create data from a form and send it to the database, there is no document id available for updating my local array of objects. ...

Utilizing a JSON object passed from one JavaScript function to another: A comprehensive guide

After creating a function that returns JSON format through an ajax call, I received the following JSON data: { "communication": [{ "communication_name": "None", "communication_id": "1" }], "hardware": [{ "hardware_name ...

Customized queries based on conditional routes - expressjs

Can we customize queries based on optional routes? app.get('/:category/:item?', function (req, res) { var category = req.params.category; var item = req.params.item; var sqlQuery = 'SELECT * FROM items WHERE category = ? AND item = ?&a ...

Vue allows a child component to share a method with its parent component

Which approach do you believe is more effective among the options below? [ 1 ] Opting to utilize $emit for exposing methods from child components to parent components $emit('updateAPI', exposeAPI({ childMethod: this.childMethod })) OR [ 2 ] ...

Could anyone please assist me in identifying any issues in my Redux state?

MODIFY The state component that is not rendering is known as TournamentShow, which fetches the state and necessary functions for the Show page. Nested inside it is a conditional to display one of three pages based on: Tournament.Status === "Open&qu ...

Is there a reason for the absence of the Revit category attribute in the JSON response retrieved from the GET request :urn/metadata/:guid/

After receiving the information from the endpoint regarding Revit Models uploaded to my bucket, I noticed that the JSON response contains multiple objects. These objects seem to represent Revit elements, each with all parameters except for the Revit Categ ...

Error encountered while generating Next.js static website in production

I am encountering errors when I try to export my project using npm run build. Oddly, everything works fine when I test with npm run dev. My code utilizes both getStaticProps and getStaticPath to fetch data from an API route. When I run npm run build I rec ...

moving all duplicate elements in an array into a separate array

I am struggling to achieve the result [1,1,1,1,2,2,20,20] from the given array. My goal is to extract all duplicate values into a new array, but I just can't seem to get it right. Can you please assist me? const array = [1, 2, 4, 591, 392, 391, 2, ...

Tips for ensuring your webpage stays current with regular updates through JavaScript

This webpage acts as a dynamic newsboard, constantly updated with the latest data from my Database through an API, all without requiring a page refresh. While the timer solution seemed simple, I am seeking a more resource-efficient approach. I have resear ...