Monday, December 23, 2024

Observable pattern- jQuery

 The key concept here is that there is an object, often referred to as the observable/subject whose internal state changes during its lifetime.


There are several other objects, referred to as observers, that want to be notified in the event that the state of the observable changes in order to execute some operations.


In most common implementation, the observable maintains a list with its observables and notifies them when an appropriate state change occurs.


So in case a state change occurs to the observable, it iterates through the list of observers that are interested for that type of state change and execute a specific method that they have defined.


The observers are described as objects that implement a well-known programming interface, in most cases, specific to each observable they are interested in.
In the case of state change, the observable will execute the well known method of each observer as it defined in the programming interface.


// Observable

const WeatherStation = (function () {

    const $observable = $({}); // jQuery object for custom events


    return {

        // Register an observer (subscribe to an event)

        on: function (event, handler) {

            $observable.on(event, handler);

        },


        // Unregister an observer

        off: function (event, handler) {

            $observable.off(event, handler);

        },


        // Notify observers (trigger the event)

        setMeasurements: function (data) {

            console.log("Weather station state changed:", data);

            $observable.trigger("stateChange", [data]);

        },

    };

})();


// Observer

function displayWeather(event, data) {

    console.log(`Current conditions: ${data.temperature}°C, ${data.humidity}% humidity, ${data.pressure} hPa.`);

}


// Usage

$(document).ready(function () {

    // Register the observer

    WeatherStation.on("stateChange", displayWeather);


    // Simulate state change

    WeatherStation.setMeasurements({ temperature: 25, humidity: 65, pressure: 1013.1 });

    WeatherStation.setMeasurements({ temperature: 28.5, humidity: 70, pressure: 1009.2 });


    // Optional: Unregister the observer

    // WeatherStation.off("stateChange", displayWeather);

});

No comments:

Post a Comment