Automatically generated VueJS function

Creating a logging system for my Javascript Project using VueJS and Vuex

To make logging methods accessible to all components, I am utilizing a global Mixin :

import { mapState, mapActions } from 'vuex'
import LogLevel from '@/enums/logger/LogLevel'

export default {
    computed: {
        ...mapState('Logger', {
            global_logs: 'activities'
        })
    },
    methods: {
        ...mapActions('Logger', {
            clear_logs: 'clear_activities'
        }),

        log_handler(message, data = {}, options = {}) {
            this.$store.dispatch('Logger/add_activity', {
                message: message,
                payload: data,
                ...options,
            });
        },

        log(message, data = {}, options = {}) {
            options.level = options.level ? options.level : LogLevel.INFO;
            this.log_handler(message, data, options);
        },

        log_debug(message, data = {}, options = {}) {
            options.level = LogLevel.DEBUG;
            this.log_handler(message, data, options);
        },

        log_info(message, data = {}, options = {}) {
            options.level = LogLevel.INFO;
            this.log_handler(message, data, options);
        },

        log_error(message, data = {}, options = {}) {
            options.level = LogLevel.ERROR;
            this.log_handler(message, data, options);
        },

        log_warning(message, data = {}, options = {}) {
            options.level = LogLevel.WARNING;
            this.log_handler(message, data, options);
        },

        log_success(message, data = {}, options = {}) {
            options.level = LogLevel.SUCCESS;
            this.log_handler(message, data, options);
        }
    }
}

And here is the enumeration utilized :

export const LogLevel = Object.freeze({
    DEBUG: "secondary",
    INFO: "info",
    WARNING: "warning",
    ERROR: "danger",
    SUCCESS: "success"
});

I am exploring options for dynamically declaring these functions. For instance, creating a method automatically for each $l Level in LogLevel:

log_$l(message, data = {}, options = {}) {
    options.level = LogLevel.$l;
    this.log_handler(message, data, options);
}

Any suggestions would be appreciated.

Answer №1

A solution is available here: https://jsfiddle.net/rhw7uj9L/

const LogLevel = Object.freeze({
    DEBUG: "secondary",
    INFO: "info",
    WARNING: "warning",
    ERROR: "danger",
    SUCCESS: "success"
})

const fns = Object.keys(LogLevel).map(level => {
    return {
        ['log_' + level.toLowerCase()] (message, data = {}, options = {}) {
            options.level = LogLevel[level]
            this.log_handler(message, data, options)
        }
    }
})

const methods = Object.assign(...fns)

new Vue({
  el: "#app",
  data: {},
  methods: {
    log_handler (message, data, options) {
        console.log('logging', message, data, options)
    },
    ...methods
  },
  created () {
    this.log_handler('olas')
    this.log_warning('yess')
    this.log_error('noppp')
  }
})

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

Switch between showing the Font Awesome TitleText and its associated Class with a single click

Can the value of the title attribute for <i> be toggled? For example, if the title is set to <i title="Favorite This Post" class="fa fa-star-o" aria-hidden="true"> within <div class="postoption"> I would like to toggle both the title te ...

How can a list of objects in a JPA entity with a many-to-one relation to a data entity be sorted based on the result of a method call from the data entity?

In my JPA entity User, there is a OneToMany relation to a UserStats entity. I made changes to the code to use UserStats instead of storing victoryRatio directly in the User entity. Now, calculateVictoryRatio() method is implemented in the UserDetails entit ...

What is the best way to specify svg attributes in virtual-dom?

Can attributes be added to SVG nodes using virtual-hyperscript in a virtual dom? Like this: var h = require('virtual-dom/h') h('svg', [ h('circle', {cx: 100, cy: 100}, 'some text') ]) I attempted this but the ...

I developed a straightforward MVC application that sends an HttpGet request and delivers an array containing 7 randomly generated, unidentified numbers to the View. [RESOLVED

A new MVC app was launched with a simple task of generating 7 random numbers between 0 and 9 to be placed at positions 1 through 7 (without starting with 0). Initially, the numbers are hidden with "X" marks. When the user clicks on the "Submit" button and ...

Tips for concealing JavaScript files from the Chrome Developer Tools while using Next.js

Currently working on a project using Next.js. I've noticed that the utils/components are quite visible through the Chrome Developer Tools, as shown in this image: Is there a way to hide them from being easily accessible? And most importantly, is it s ...

Functionality fails to load correctly post completion of AJAX request

After successfully implementing an API call to OS Maps (UK map builder) as per their documentation, I encountered a problem when trying to display a map based on a custom field name using ACF (Advanced Custom Fields) in WordPress. The issue arises because ...

What prevents variables defined in outer blocks from being accessed by nested describe() blocks?

In my real code, I encountered a problem that I wanted to demonstrate with a simple example. The code below functions properly. I defined a variable in the root describe() block that can be accessed in the it() blocks of nested describe()s. describe(&apo ...

Sending javascript data to php within a modal popup

I am currently working on passing a javascript variable to php within a modal window, all while remaining on the same page (edit.php). Although I plan to tackle handling this across separate pages later on, for now, I have successfully implemented the foll ...

What is the best way to transfer values or fields between pages in ReactJS?

Is there a way to pass the checkbox value to the checkout.js page? The issue I'm facing is on the PaymentForm page, where my attempts are not yielding the desired results. Essentially, I aim to utilize the PaymentForm fields in the checkout.js page as ...

Troubleshooting layout problems caused by positioning items at window height with CSS and jQuery

At this moment, my approach involves utilizing jQuery to position specific elements in relation to the window's size. While this method is effective when the window is at its full size, it encounters issues when dealing with a debugger that's ope ...

The Vuex action is unable to execute a mutation

I am currently working on implementing an authentication feature for a website using Firebase. Whenever a user logs into Firebase, my store's action is triggered, which in turn commits a mutation to set the state with the userID. However, I keep encou ...

A step-by-step guide on fetching multiple iframe contents simultaneously with Selenium in Java

Today, I am facing an interesting challenge. I need to extract the page source of a webpage that includes an iframe. Surprisingly, when using the PhantomJSDriver with the code snippet below, I am only able to retrieve either the page content or the iframe ...

Issues arising from the implementation of AJAX forms

Currently, I am working with Ruby on Rails 3.1.1 and using the jquery-rails 1.0.16 gem in my project. The issue I am facing involves utilizing a form with :remote => true. Within my view file, the form snippet looks like this: <%= form_for(@user, : ...

Issue with child rows not functioning properly in DataTables when utilizing Datetime-moment

I've successfully integrated this data into live.datatables.net and almost have it running smoothly. However, I am encountering an issue with displaying the last detail as a child element. The final part of the row should be shown with the label "Mes ...

Unit testing in Angular JS is crucial, especially when testing functions in services that do not return any values

Apologies if this has been asked before, but I couldn't find a solution to my issue. I need to create tests for a service within an Angular JS application. The main function of the service returns and is used as an external method. There are also a ...

Is there a more efficient method for invoking `emit` in Vue's Composition API from an external file?

Is there a more efficient way to access the emit function in a separate logic file? This is my current approach that is functioning well: foo.js export default (emit) => { const foo = () => { emit('bar') }; return { foo }; } When ...

Choose a division of an element within an embedded frame

Two different pages on the same website, Home.html and Page2.html. Home.html contains the following code: <html> <iframe id="one" src="page2.html" style="display:none"></iframe> <div id="container"> <h1& ...

Manipulating a specific element within an ng-repeat in AngularJS without affecting the others

I'm currently working on developing a basic single page application to monitor people's movements. While I've made good progress, I've encountered an issue with the click function in the child elements of each person div. When I try to ...

Passing in additional custom post data alongside serializing with jQuery

function MakeHttpRequest( args ) { var dataToSend = "?" + $("form[name=" + args.formName + "]").serialize(); $.ajax({ type: "POST", url: args.url + dataToSend, data: { request: args.request }, su ...

Moving a DOM element within AngularJS to a new location

I have created an angular directive that functions like a carousel. To keep the dom element count low, I delete elements from the dom and then re-insert them using angular.element to select, remove, and insert items as shown below: app.directive('myD ...