<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Ashok</title>
    <description>The latest articles on DEV Community by Ashok (@ashok_24_99c5ee15c6ad5150).</description>
    <link>https://dev.to/ashok_24_99c5ee15c6ad5150</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F1505238%2Fa3c631d0-ff03-42f4-9669-4b0fec26699a.jpg</url>
      <title>DEV Community: Ashok</title>
      <link>https://dev.to/ashok_24_99c5ee15c6ad5150</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/ashok_24_99c5ee15c6ad5150"/>
    <language>en</language>
    <item>
      <title>Building a Reactive Store in React Using the Observer Design Pattern and Custom Hook</title>
      <dc:creator>Ashok</dc:creator>
      <pubDate>Sat, 17 Aug 2024 12:52:21 +0000</pubDate>
      <link>https://dev.to/ashok_24_99c5ee15c6ad5150/building-a-reactive-store-in-react-using-the-observer-design-pattern-and-custom-hook-41kl</link>
      <guid>https://dev.to/ashok_24_99c5ee15c6ad5150/building-a-reactive-store-in-react-using-the-observer-design-pattern-and-custom-hook-41kl</guid>
      <description>&lt;p&gt;In modern React development, managing state across components can be challenging, especially when you want to keep different components in sync with shared state. One effective solution to this problem is using the Observer Design Pattern combined with a custom hook in React. In this article, we'll walk through how to implement a simple reactive store using the Observer pattern and leverage it in a React application.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 1: Implementing the ObserverPattern Class&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The Observer Pattern is a behavioral design pattern where an object (known as the subject) maintains a list of its dependents (observers) and notifies them of any state changes. Here’s how we can implement it in JavaScript:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class ObserverPattern {
    constructor(initialState = {}) {
        this.state = initialState;
        this.observers = [];
    }

    subscribe(event) {
        this.observers.push(event);
    }

    notify() {
        this.observers.forEach(observer =&amp;gt; observer(this.state));
    }

    setState(newState) {
        this.state = { ...this.state, ...newState };
        this.notify();
    }

    getState() {
        return this.state;
    }

    unsubscribe(event) {
        this.observers = this.observers.filter(observer =&amp;gt; observer !== event);
    }
}

const Store = new ObserverPattern({ count: 10 });

export default Store;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Explanation:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;State Management: The ObserverPattern class holds the state in the state object and provides methods to update (setState) and access (getState) this state.&lt;/li&gt;
&lt;li&gt;Observer List: The observers array stores the functions that should be called whenever the state changes.&lt;/li&gt;
&lt;li&gt;Notify Method: The notify method iterates over all observers and triggers them with the current state, ensuring that any subscribed component gets updated.&lt;/li&gt;
&lt;li&gt;Unsubscribe Method: This method removes a specific observer from the list to avoid memory leaks.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Step 2: Creating a Custom Hook for React Components&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The next step is to create a custom hook, useStore, that allows React components to interact with our ObserverPattern store.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { useEffect, useState } from "react";
import Store from "./customhook";

const useStore = (selector) =&amp;gt; {
    const [state, setState] = useState(selector(Store.getState()));

    useEffect(() =&amp;gt; {
        const event = (newState) =&amp;gt; {
            setState(selector(newState));
        };

        Store.subscribe(event);

        return () =&amp;gt; {
            Store.unsubscribe(event);
        };
    }, [selector]);

    return state;
};

export default useStore;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Explanation:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Selector Function: The useStore hook accepts a selector function to pick specific parts of the state. This makes it flexible and efficient by only updating when the selected state changes.&lt;/li&gt;
&lt;li&gt;State Synchronization: The hook initializes local state with the selected part of the store’s state. When the store’s state changes, the hook updates the component’s state, triggering a re-render.&lt;/li&gt;
&lt;li&gt;Effect Hook: The useEffect hook handles subscribing to the store on mount and unsubscribing on unmount, ensuring that the component stays in sync with the store while avoiding memory leaks.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Step 3: Using the Store in React Components&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Now, let's see how we can use this custom hook within React components to manage and display the state.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Parent Component:&lt;/strong&gt;&lt;br&gt;
The Parent component provides a button to increment the count state in the store.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import Store from "./customhook";

const Parent = () =&amp;gt; {
    let count = Store.getState().count;
    const increase = () =&amp;gt; {
        ++count;
        Store.setState({ count });
    }

    return (
        &amp;lt;&amp;gt;
            &amp;lt;button onClick={increase}&amp;gt;Increase&amp;lt;/button&amp;gt;
        &amp;lt;/&amp;gt;
    );
}

export default Parent;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Child Components:&lt;/strong&gt;&lt;br&gt;
Both ChildComponentOne and ChildComponentTwo subscribe to the count state using the useStore hook.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import useStore from "./customhook"; // custom hook

const ChildComponentOne = () =&amp;gt; {
    const count = useStore(state =&amp;gt; state.count);

    return (&amp;lt;&amp;gt;ChildComponentOne = {count}&amp;lt;/&amp;gt;)
}

export default ChildComponentOne;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import useStore from "./customhook";

const ChildComponentTwo = () =&amp;gt; {
    const count = useStore(state =&amp;gt; state.count);

    return (&amp;lt;&amp;gt;ChildComponentTwo = {count}&amp;lt;/&amp;gt;)
}

export default ChildComponentTwo;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Explanation:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Parent Component: The Parent component manages the increase function, which increments the count and updates the store. Both child components are rendered below the button.&lt;/li&gt;
&lt;li&gt;Child Components: These components are connected to the store via the useStore hook. Whenever the count state in the store changes, they automatically re-render to reflect the new value.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Conclusion&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;By leveraging the Observer Design Pattern and custom hooks, you can create a powerful and flexible state management solution in React. This approach allows you to easily keep multiple components in sync without relying on more complex state management libraries. The separation of concerns between state management and UI components also makes the code more maintainable and reusable.&lt;/p&gt;

&lt;p&gt;Feel free to adapt this pattern to suit your project’s needs, and enjoy the reactive power of your new custom store in React!&lt;/p&gt;

</description>
    </item>
    <item>
      <title>🚀🚀 Integrating the PubSub Pattern in Vue 3 🚀🚀</title>
      <dc:creator>Ashok</dc:creator>
      <pubDate>Thu, 15 Aug 2024 08:43:44 +0000</pubDate>
      <link>https://dev.to/ashok_24_99c5ee15c6ad5150/integrating-the-pubsub-pattern-in-vue-3-1h83</link>
      <guid>https://dev.to/ashok_24_99c5ee15c6ad5150/integrating-the-pubsub-pattern-in-vue-3-1h83</guid>
      <description>&lt;p&gt;As Vue.js applications grow, managing communication between components can become complex. A powerful solution to decouple components and manage event-driven communication is the Publish-Subscribe (PubSub) pattern. By integrating this pattern into Vue.js, you can create a flexible and maintainable way to handle events across your application.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;What is the PubSub Pattern?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The PubSub pattern allows components to publish events that other components can subscribe to. This decouples components, making your application more modular and easier to manage. Using PubSub, you can trigger actions or update states in one component based on events in another without needing direct parent-child communication.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Implementing the PubSub Pattern in Vue.js&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Let’s walk through how to implement the PubSub pattern in a Vue.js application using a simple, reusable event bus.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 1: Create a PubSub Event Bus&lt;/strong&gt;&lt;br&gt;
In Vue.js, you can create a simple event bus using Vue’s provide and inject APIs or by creating a standalone PubSub object.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// pubsub.js
export const PubSub = {
    subscribers: new Map(),

    subscribe(event, subscriber) {
        if (!this.subscribers.has(event)) {
            this.subscribers.set(event, []);
        }
        this.subscribers.get(event).push(subscriber);
    },

    unsubscribe(event, subscriber) {
        if (this.subscribers.has(event)) {
            const updatedSubscribers = this.subscribers.get(event).filter(sub =&amp;gt; sub !== subscriber);
            if (updatedSubscribers.length &amp;gt; 0) {
                this.subscribers.set(event, updatedSubscribers);
            } else {
                this.subscribers.delete(event);
            }
        }
    },

    publish(event, payload) {
        if (this.subscribers.has(event)) {
            this.subscribers.get(event).forEach(subscriber =&amp;gt; {
                subscriber(payload);
            });
        }
    }
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;Step 2: Using PubSub in Vue Components&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Now that you have your PubSub event bus, you can use it in your Vue components to subscribe to events, publish events, and unsubscribe when the component is destroyed.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Component-1&lt;/strong&gt;&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;template&amp;gt;
  &amp;lt;div&amp;gt;SubscriberComponent-1 {{ count }}&amp;lt;/div&amp;gt;
&amp;lt;/template&amp;gt;

&amp;lt;script  setup&amp;gt;
import { onMounted, ref } from "vue";
import { PubSub } from "./pubsub.js";

const count = ref(0);

const event = (payload) =&amp;gt; {
  console.log("Received payload:", payload);
  count.value = payload;
};

onMounted(() =&amp;gt; {
  PubSub.subscribe("myEvent", event);
});
&amp;lt;/script&amp;gt;


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;Component-2&lt;/strong&gt;&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;template&amp;gt;
  &amp;lt;div&amp;gt;SubscriberComponent-2 {{ count }}&amp;lt;/div&amp;gt;
&amp;lt;/template&amp;gt;

&amp;lt;script  setup&amp;gt;
import { onMounted, ref } from "vue";
import { PubSub } from "./pubsub.js";

const count = ref(0);

const event = (payload) =&amp;gt; {
  console.log("Received payload:", payload);
  count.value = payload;
};

onMounted(() =&amp;gt; {
  PubSub.subscribe("myEvent", event);
});
&amp;lt;/script&amp;gt;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;Publishing an Event:&lt;/strong&gt;&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;template&amp;gt;
  &amp;lt;div&amp;gt;PublisherComponent &amp;lt;button @click="publishEvent"&amp;gt;post&amp;lt;/button&amp;gt;&amp;lt;/div&amp;gt;
&amp;lt;/template&amp;gt;

&amp;lt;script  setup&amp;gt;
import { PubSub } from "./pubsub.js";

let count = 1;

const publishEvent = () =&amp;gt; {
  ++count;
  PubSub.publish("myEvent", { message: `Hello, PubSub! ${count}` });
};
&amp;lt;/script&amp;gt;


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F7ofbkkcwjyvoaj4xmds9.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F7ofbkkcwjyvoaj4xmds9.png" alt="Image description"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Why Use the PubSub Pattern in Vue.js?&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Decoupling: The PubSub pattern helps to decouple components, making your application more modular and easier to maintain.&lt;/li&gt;
&lt;li&gt;Event-Driven Architecture: It enables an event-driven approach, where components can react to events without being directly connected.&lt;/li&gt;
&lt;li&gt;Flexibility: The PubSub pattern allows you to manage events across different parts of your application without the need for complex prop drilling or state management.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Conclusion&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;By integrating the PubSub pattern into Vue.js, you can manage communication between components more effectively, leading to a cleaner, more modular application architecture. This pattern is particularly useful for large applications where components need to communicate frequently without becoming tightly coupled.&lt;/p&gt;

&lt;p&gt;Feel free to use this approach in your own Vue.js projects, and adapt it to suit your needs. Happy coding!&lt;/p&gt;

</description>
    </item>
    <item>
      <title>🚀🚀 Integrating the PubSub Pattern in React with a Custom Hook 🚀🚀</title>
      <dc:creator>Ashok</dc:creator>
      <pubDate>Thu, 15 Aug 2024 08:11:05 +0000</pubDate>
      <link>https://dev.to/ashok_24_99c5ee15c6ad5150/integrating-the-pubsub-pattern-in-react-with-a-custom-hook-2jib</link>
      <guid>https://dev.to/ashok_24_99c5ee15c6ad5150/integrating-the-pubsub-pattern-in-react-with-a-custom-hook-2jib</guid>
      <description>&lt;p&gt;In modern React applications, managing communication between components can be challenging, especially as your project scales. A common solution to decouple components and manage event-driven communication is the Publish-Subscribe (PubSub) pattern. By integrating this pattern as a custom hook in React, you can create a flexible and powerful way to handle events across your application.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;What is the PubSub Pattern?&lt;/strong&gt;&lt;br&gt;
The PubSub pattern is a design pattern that allows components to publish events and other components to subscribe to those events. This decouples the components, making your application more modular and easier to manage. With PubSub, you can trigger actions or update states in one component based on events in another, without direct prop passing or tightly coupling your components.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Implementing the PubSub Pattern as a Custom Hook in React&lt;/strong&gt;&lt;br&gt;
Here's how you can integrate the PubSub pattern into a React application by creating a custom hook.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 1: Create the usePubSub Hook&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;First, we define the usePubSub hook, which will provide the functionality to subscribe to events, publish events, and unsubscribe when a component unmounts.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { useEffect, useRef } from 'react';

const PubSub = {
    subscribers: new Map(),

    subscribe: function (event, subscriber) {
        if (!this.subscribers.has(event)) {
            this.subscribers.set(event, []);
        }
        this.subscribers.get(event).push(subscriber);
    },

    unsubscribe: function (event, subscriber) {
        if (this.subscribers.has(event)) {
            const subscribers = this.subscribers.get(event).filter(sub =&amp;gt; sub !== subscriber);
            this.subscribers.set(event, subscribers);
        }
    },

    publish: function (event, payload) {
        if (this.subscribers.has(event)) {
            this.subscribers.get(event).forEach(subscriber =&amp;gt; {
                subscriber(payload);
            });
        }
    }
};

export const usePubSub = (event, handler) =&amp;gt; {
    const handlerRef = useRef();

    useEffect(() =&amp;gt; {
        handlerRef.current = handler;
    }, [handler]);

    useEffect(() =&amp;gt; {
        const eventHandler = (payload) =&amp;gt; handlerRef.current(payload);
        PubSub.subscribe(event, eventHandler);

        return () =&amp;gt; {
            PubSub.unsubscribe(event, eventHandler);
        };
    }, [event]);

    const publish = (payload) =&amp;gt; {
        PubSub.publish(event, payload);
    };

    return publish;
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Step 2: Using the usePubSub Hook in Your Components&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;You can create multiple SubscriberComponent and get the message from the PublisherComponent.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React from 'react';
import { usePubSub } from './usePubSub';

const SubscriberComponent = () =&amp;gt; {
    usePubSub('myEvent', (payload) =&amp;gt; {
        // using this event you can do the actions
        console.log('Received payload:', payload);
    });

    return &amp;lt;div&amp;gt;Subscribed to myEvent&amp;lt;/div&amp;gt;;
};

export default SubscriberComponent;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Publishing an Event:&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React from 'react';
import { usePubSub } from './usePubSub';

const PublisherComponent = () =&amp;gt; {
    const publish = usePubSub('myEvent',()=&amp;gt;{});

    const handleClick = () =&amp;gt; {
        publish({ message: 'Hello, PubSub!' });
    };

    return &amp;lt;button onClick={handleClick}&amp;gt;Publish Event&amp;lt;/button&amp;gt;;
};

export default PublisherComponent;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Why Use the PubSub Pattern in React?&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Decoupling: The PubSub pattern helps to decouple components, making your application more modular and easier to maintain.&lt;/li&gt;
&lt;li&gt;Event-Driven Architecture: It enables an event-driven approach, where components can react to events without being directly connected.&lt;/li&gt;
&lt;li&gt;Flexibility: With the usePubSub hook, you can easily manage events across different parts of your application without needing to pass props or manage complex state hierarchies.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Conclusion&lt;/strong&gt;&lt;br&gt;
By integrating the PubSub pattern into React as a custom hook, you can manage communication between components more effectively. This approach allows for a cleaner, more modular application architecture, making your React projects easier to scale and maintain.&lt;/p&gt;

&lt;p&gt;Feel free to use this pattern in your own projects and adapt it to fit your specific needs. Happy coding!&lt;/p&gt;

</description>
    </item>
    <item>
      <title>Understanding the PubSub (Publish-Subscribe) Design Pattern in JavaScript</title>
      <dc:creator>Ashok</dc:creator>
      <pubDate>Wed, 14 Aug 2024 11:42:55 +0000</pubDate>
      <link>https://dev.to/ashok_24_99c5ee15c6ad5150/understanding-the-pubsub-publish-subscribe-design-pattern-in-javascript-3o35</link>
      <guid>https://dev.to/ashok_24_99c5ee15c6ad5150/understanding-the-pubsub-publish-subscribe-design-pattern-in-javascript-3o35</guid>
      <description>&lt;p&gt;The Publish-Subscribe (PubSub) pattern is a popular design pattern used to facilitate communication between different parts of an application without them needing to know about each other directly. This pattern is especially useful for decoupling components in large-scale applications, where events can be published and subscribers can react to these events.&lt;/p&gt;

&lt;p&gt;In this article, we'll explore how to implement the PubSub pattern in JavaScript using both an object-based approach and a class-based approach. By the end, you'll have a solid understanding of how to use this pattern in your own projects.&lt;/p&gt;

&lt;p&gt;Object-Based Implementation&lt;br&gt;
The object-based approach is simple and effective for scenarios where a single global event manager is sufficient. Here's how you can implement it:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;pubsub.js
const PubSub = {
    subscribers: [],

    subscribe: function(subscriber) {
        this.subscribers.push(subscriber);
    },

    publish: function(payload) {
        this.subscribers.forEach(subscriber =&amp;gt; {
            subscriber(payload);
        });
    }
};

export default PubSub;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;How to Use the Object-Based PubSub&lt;br&gt;
In your application, you can import the PubSub object wherever you need it. Here’s an example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// file1.js
import PubSub from './pubsub';

PubSub.subscribe((payload) =&amp;gt; {
    console.log('File 1 received:', payload);
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// file2.js
import PubSub from './pubsub';

PubSub.subscribe((payload) =&amp;gt; {
    console.log('File 2 received:', payload);
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// main.js
import PubSub from './pubsub';

PubSub.publish('Hello from main!');
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Class-Based Implementation&lt;br&gt;
For more flexibility or when you need multiple instances of a PubSub system, a class-based approach can be used. This allows you to create independent PubSub instances with their own list of subscribers.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class PubSub {
    constructor() {
        this.subscribers = [];
    }

    subscribe(subscriber) {
        this.subscribers.push(subscriber);
    }

    unsubscribe(subscriber) {
        this.subscribers = this.subscribers.filter(sub =&amp;gt; sub !== subscriber);
    }

    publish(payload) {
        this.subscribers.forEach(subscriber =&amp;gt; {
            try {
                subscriber(payload);
            } catch (error) {
                console.error('Error in subscriber:', error);
            }
        });
    }
}

export default PubSub;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;How to Use the Class-Based PubSub&lt;br&gt;
Here's an example of how you can use the class-based PubSub pattern in your application:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import PubSub from './pubsub';

// Create an instance of PubSub
const pubSubInstance = new PubSub();

// Subscribe to events
pubSubInstance.subscribe((payload) =&amp;gt; {
    console.log('Instance 1 received:', payload);
});

pubSubInstance.subscribe((payload) =&amp;gt; {
    console.log('Instance 2 received:', payload);
});

// Publish an event
pubSubInstance.publish('Hello from instance!');

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Conclusion&lt;br&gt;
The PubSub pattern is a powerful tool for managing communication between different parts of your application. Whether you choose to use an object-based or class-based implementation depends on your specific needs. The object-based approach is simple and straightforward, ideal for smaller projects or when a single global event manager is sufficient. On the other hand, the class-based approach offers more flexibility and is better suited for larger applications where you may need multiple instances of the PubSub system.&lt;/p&gt;

&lt;p&gt;Feel free to use these examples in your own projects and modify them to suit your needs. Happy coding!&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>designpatterns</category>
    </item>
  </channel>
</rss>
