loading...

Observer Pattern example in Javascript

nitin1104 profile image Nitin Bhatnagar ・1 min read

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);

Posted on by:

nitin1104 profile

Nitin Bhatnagar

@nitin1104

Hi I am a big time foodie love to cook and eat spicy food and web developer having rich experience in UX design and learn #javascript

Discussion

pic
Editor guide