DEV Community

Nitin Bhatnagar
Nitin Bhatnagar

Posted on

3 2

Observer Pattern example in Javascript

This is an example of observer pattern in Javascript with the example of weather updates. Kindly wrap this function in
(function(window) {IFFE})(window);

var weatherForcast = {

        /* observer is a list of subscribers.*/
    observers: [],

        /*weatherChange function will have updated weather*/
    weatherChange: function (weather) {
        for (var i = 0; i < this.observers.length; i++) {
                this.observers[i].updateUI(weather);
        }
    },

    /* subscribe function will add a subscriber in observer's list.*/
    subscribe: function (widget) {
        this.observers.push(widget);
        var self=this;
        return function(){
                self.observers.splice(self.observers.indexOf(widget), 1);
        };
    },

    /* Unsubscribe function will remove a subscriber from observer's list.*/
    unsubscribe: function(){
        this.observers.splice(this.observers.indexOf(Widget), 1)
    }
};

/* Constructor function for Widget(Subscribers).*/
function Widget(name){
    this.name = name;
}

/* function to update all the Subscribers when weather change.*/
Widget.prototype.updateUI = function(weather){
    console.log('Weather in ' + this.name + ' is ' + weather + '\xB0C');
};

/* Creating widgets using constructor function*/
var x1 = new Widget('New Delhi');
var x2 = new Widget('Gurgaon');
var x3 = new Widget('Faridabad');

/* Subscribing for weather updates*/
var unsubx1 = weatherForcast.subscribe(x1);
var unsubx2 = weatherForcast.subscribe(x2);
var unsubx3 = weatherForcast.subscribe(x3);

/* weather updated */
weatherForcast.weatherChange(10);

console.log('========================');

    /* unsubscribing one widget */
unsubx3();

/* weather updated */
weatherForcast.weatherChange(11);

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay