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

Function cascading

I'm currently facing a slight confusion with the got module, available at https://www.npmjs.com/package/got. The sequence and structure of functions within this module has got me puzzled. It's clear that you can chain listeners and functions toge ...

Enhance your web forms with jQuery Chosen's automatic formatting feature

Having trouble adding a feature to my multi-select input box using jQuery Chosen. The current functionality allows users to enter custom values not in the list. The new feature should automatically format numbers entered by users, for example: User input ...

The specified 'Object' type does not match the required 'Document' constraint

I need assistance with running a MERN application to check for any issues, but I keep encountering this error across multiple files. Error: The 'CatalogType' type does not meet the requirements of 'Document'. The 'CatalogType&apo ...

What could be causing this `even` function to malfunction when utilizing getElementById?

Need assistance with utilizing document.getElementById? Let's take a look at this code snippet: function even() for (i = 0; i < 10; i++) { if (i % 2 == 0) { alert(i); } } document.getElementById("even").innerHTML = i + &apos ...

Swap a jQuery class with another if the class for ul li is currently active

I am currently developing a form builder and I would like to customize the appearance, specifically changing the color of the text. I want the text to be white when the class is set to active, and black when the class is not active. Is there a way to achi ...

Is there a way for me to modify a value in Mongoose?

I have been attempting to locate clients by their ID and update their name, but so far I haven't been successful. Despite trying numerous solutions from various sources online. Specifically, when using the findOneAndUpdate() function, I am able to id ...

Checking for at least one matching pair in a JavaScript object

I have a pair of dictionaries that I need to compare in JavaScript. The goal is to determine if there is at least one identical key-value pair between them, not necessarily the entire dictionary being identical. my_dict = {"Text1":"Text1", "Text2":"Text3", ...

Title: Propagating error responses through nested async/await try/catch blocks in NodeJS

I'm struggling to handle error responses in nested try/catch blocks within an Express route handler. In the given code snippet, I want the route handler to stop execution if an error is caught in the inner Try/Catch 3 block, resulting in a 404 status ...

Warning: Datatables encountered an issue with the table ID 'example'

Good day, I am seeking clarification regarding DataTables. In a tutorial, I came across a table that can be edited "inline". I prefer the table to be in German. The code snippet for the table: <script type="text/javascript" language="javascript" ...

The TypeScript compiler is generating node_modules and type declaration files in opposition to the guidelines outlined in the tsconfig.json file

For the past week, I've been trying to troubleshoot this issue and it has me completely puzzled. What's even more puzzling is that this app was compiling perfectly fine for months until this problem occurred seemingly out of nowhere without any c ...

Centering an image that is absolutely positioned within a container that is relatively positioned, horizontally

Looking to center an image that is positioned absolutely horizontally within a container that is relatively positioned. After attempting with CSS and not finding success, I ended up using Jquery. http://jsfiddle.net/CY6TP/ [This is my attempt using Jquery ...

Learn how to render a dynamic checkbox that is connected with AJAX and PHP for seamless functionality

I need to showcase a dynamic checkbox that can be bound using ajax and php. Here is my code: <?php include 'dbconnect.php'; $result = mysqli_query($link, "SELECT * FROM city where district_id='$dist' "); while($city_row=mysqli_fe ...

I'm attempting to utilize a basic webcam capture upload feature, but it seems that the upload function is not functioning properly

UPDATE: This is the complete code that I simply copied and pasted. <!DOCTYPE HTML> <head> <script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script> <script language="JavaScript" type="text/javascrip ...

Get back a variety of substitutions

I have a variety of different text strings that I need to swap out on the client side. For example, let's say I need to replace "Red Apple" with "Orange Orange" and "Sad Cat" with "Happy Dog". I've been working on enhancing this particular ques ...

ESLint prohibits the usage of React.StatelessComponent and React.FunctionalComponent within the codebase

Is there a way to restrict the use of React.StatelessComponent or React.FunctionalComponent and only allow React.FC in my code? For instance: export const ComponentOne: React.StatelessComponent<Props> = (props) => { return <....> }; export ...

JavaScript: a highly effective method for verifying if a variable is a function, an array, or an object

Imagine a scenario where we have a variable that could potentially be a function, object, or array. I am in search of the most efficient method to determine its type. In my opinion, the current approach is not optimized because if I already know that isF ...

What is the process for removing a particular file from my bundle?

I am currently utilizing webpack to build my angular2/typescript application and have successfully generated two files, one for my code and another for vendors. However, I am in need of a third file to separate my config (specifically for API_ENDPOINT) whi ...

Utilizing AngularJS: Transforming JSONP information into HTML

I'm relatively new to utilizing $http and fetching data from various websites. My main query is, how can I convert JSONP into HTML? Specifically, when using $http to request the Atari Wikipedia page, the content is displayed with and HTML elements. ...

Creating Angular Modal on ng-click

I'm facing a challenge with a seemingly simple task. Within an ng-repeat, I have a table of events. My goal is to enable users to click on the event name and view detailed information in a modal window. To achieve this, I have set up an ng-click="ev ...

Utilizing Chart.js with Vue for dynamic time axis plots from JSON data through computed properties

Trying to generate a chart with a time axis in Vue using Chart.js has been a challenge. Initially, everything worked perfectly when the data was set directly in the Data object as shown below: chartData: { datasets: [ { backgroundC ...