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++) {

    /* subscribe function will add a subscriber in observer's list.*/
    subscribe: function (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 */


    /* unsubscribing one widget */

/* weather updated */

Posted on by:

nitin1104 profile

Nitin Bhatnagar


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


Editor guide