Obtain an Instance of a Class Using a Decorator

Delving deep into the world of decorators, I stumbled upon some fascinating ideas for incorporating them into my reflux implementation. My concept involves tagging a store's class method with an action, so that whenever that action is triggered, it automatically calls all associated methods.

My first step is to tag the Store method:

@Action
public setData(data: FakeData) {
    console.log(this);
    this.state.data = data;
}

Next, in the action class, I plan to register that method in an array:

class Action {
    private static methods: Method<FakeData>[] = [];

    public static register(method: Method<FakeData>) {
        this.methods.push(method);
    }

    constructor(payload: FakeData);
    constructor(store: Store, method: string);
    constructor(payload: any, method?: string, descriptor?: PropertyDescriptor) {
        if (method) {
            //TODO need actual instance of class here....
            Action.register(payload[method].bind(payload));
            return;
        }

        this.trigger(payload);
    }

    public get payload() {
        return Math.random();
    }

    private trigger(payload: FakeData) {
        Action.methods.forEach(m => m(payload));
    }
}

Unfortunately, within the constructor, I'm unable to access the actual store instance. While I can obtain the constructor, it doesn't seem like I can use that to achieve my intended functionality. Perhaps making all stores strictly static would be a better approach?

It's evident that I still have much to learn about how to effectively utilize these decorators, so any guidance or insights are more than welcome!

Explore complete code on Typescript Playground

Answer №1

Decorators appear to be invoked during the class definition rather than instantiation. As a result, all store methods had to be set as static for this approach to function properly, rendering instances inaccessible:

@Action
public static setData(data: FakeData) {
    console.log(this);
    this.state.data = data;
}

For the complete operational code, click here:

Typescript Playground

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

using a route object to update the path in Nuxt

I need to navigate to a specific URL: myApp.com/search-page?name%5Bquery%5D=value The code snippet below works perfectly when I'm on the homepage myApp.com: this.$router.push({ path: "search-page", query: { name: { query: `${this.value} ...

The error message states: "An error occurred: Unable to find the 'HttpProvider' property within an undefined

import * as Web3 from 'web3' import { OpenSeaPort, Network } from 'opensea-js' const provider = new Web3.providers.HttpProvider('https://mainnet.infura.io') Hello everyone, I'm currently learning Node.js and encountered ...

What is the best way to shuffle the displayed images on a website to make the order random?

I'm looking to create a unique collage using 10 image files in a folder with vanilla JS. The goal is to randomize the images within a Bootstrap container on a website while maintaining their aspect ratio by utilizing a grid layout. However, I've ...

How can I combine my two ngIf conditions into an ngIf else statement?

Having trouble incorporating an *ngIf else with two large <div> elements, as the content seems overwhelming to organize properly while following the documentation. Initially believed that using the same styling for two open text boxes, with one hidd ...

verify selection on php page using javascript

I'm having trouble with confirming the deletion of something. Despite getting an alert message when clicking the 'deleteReply' button, nothing else appears to be happening. I've tried echoing the posted variable but it's not workin ...

What is the best way to continuously verify login and password credentials?

I am a newcomer to this industry and am facing a challenge with testing the process of entering the correct username and password using Selenium Webdriver. The current method of creating this process without a loop is extremely lengthy and monotonous. Here ...

Crafting interactive image checkboxes

At present, the checkboxes in my application are quite basic with labels. However, our app designer has requested that we revamp this feature and make it more appealing by using clickable images that still function like checkboxes. Allow me to provide an ...

Exploring Attachments in ASP.NET Core MVC Views

I have placed attachments in a Shared Folder on a server. I attempted to access them using the <a> tag <a href="file:///C:">Open Attachments</a> Unfortunately, this method did not work in ASP.NET Core MVC for unknown reasons. I ...

What could be causing the createReadStream function to send a corrupted file?

My current task involves generating a file from a URL using the fs module to my local system. Initially, everything seems successful. However, when attempting to post this file into a group using the createReadStream() function, I encounter an issue where ...

Avoid working on the script for the element in the partial view during the event

In my index.cshtml view, I have a script that triggers an AJAX call when the SearchingManagerId2 element is changed. $("#SearchingManagerId2").on("change", function () { var valueForSearch = $(this).val(); $.ajax({ ...

The Strapi registration feature in version 4 is giving a "method not allowed 405" error, which

Feeling a bit confused with a Strapi query. I am currently working on v4 and trying to set up a registration feature. The code snippet for invoking the function is provided below. Everything seems fine, such as submitting function variables, etc. However, ...

Issues concerning date and time manipulation - Library Moment.js

As a beginner in JavaScript, I've been working on an activity that generates a table of train times based on user input. However, I'm facing issues with formatting the arrival time correctly. Whenever I input the arrival time in military format ( ...

"Make a phone call following the completion of an HTTP

Upon receiving and storing data, I am looking to execute a function but the code I currently have is not producing the desired result. Could someone provide some insight into what I might be doing incorrectly? Here's my current code snippet: $h ...

What is the best way to pass the reference of the p tag every time the button is clicked?

This is the code I used to create a button: <button type="submit" id="likebtn" onclick="likedpost(this) " data-postid="<%=blog._id%>" data-author="<%=user.username%>">Like</button> ...

How can you utilize a computed property in a Vue component to select all the text within it?

When using $event.target.select(), I usually can select all the text. However, in this scenario, it seems to be selecting everything and then replacing the selection with the computed property. How can I select all after the computed property has finished? ...

How can I address multiple buttons with various events using jQuery?

I am new to learning jQuery and I'm currently working on some exercises. However, I've run into an issue with two buttons in the DOM that are supposed to perform different actions. I can't seem to figure out how to assign different functions ...

Toggle the visibility of a component in React by managing its state

Currently, I am faced with the challenge of toggling the visibility of a component based on a state value: import React, { Component } from 'react'; import logo from './logo.svg'; import './App.css'; import Button from ' ...

Creating a HTML5 Geolocation object using Python: A step-by-step guide

For my software analytics testing, I am looking to send GET requests with a geolocation object that includes variable timestamps and locations. The website utilizes the HTML5 navigator.getcurrent.location() function. While I can use the random module to r ...

organize and identify a JSON data using sorting and matching techniques

Having a JSON structure as shown below: [ { "id": "1", "freq": "1", "value": "Tiruchengode", "label": "Tiruchengode" }, { "id": "2", "freq": "1", "value": "Coimbatore", "label": " ...

How can state values be transferred between components?

I have come across various answers on different platforms but haven't been able to achieve the desired results. That's why I am reaching out with this question. So, my question is related to 3 files named: App.js, SignUp.js, and Welcome.js. My ...