Observer Pattern in the Kitchen

how would this work?

by Andrew Holloway

HTML

<button>hi</button>

JavaScript

var Waiter = function(name) {
  this.name = name;
  this.orders = ['chicken', 'beef', 'vegan'];
};

Waiter.prototype.placeOrder = function(name) {
  if (this.orders.indexOf(name) !== -1) {
    console.log(this.name, name + ' is up!');
    this.sousChef.receiveOrder(name);
  } else {
    console.log(this.name, 'I am a waiter. I cannot handle unknown dishes');
  }
};

Waiter.prototype.assignSousChef = function(sousChef) {
  this.sousChef = sousChef;
};

// Sous Chef acts as the observer

var SousChef = function(name) {
  this.name = name;
  this.commands = {};
  this.orders = {
    'chicken': ['grill', 'steam'],
    'beef': ['grill', 'steam'],
    'vegan': ['steam', 'boil']
  };
};

// Sous Chef tell the kitchen what to do, so we give the staff a way to listen to her
SousChef.prototype.dispatchesOrder = function(toCommand, action) {
  if (!Array.isArray(this.commands[toCommand])) {
    this.commands[toCommand] = [];
  }

  this.commands[toCommand].push(action);

};

// Sous Chef can give orders out
SousChef.prototype.handleOrder = function(toCommand) {
  if (Array.isArray(this.commands[toCommand])) {
    this.commands[toCommand].forEach(function(instance) {
      instance();
    });
  }
};

// Sous chef can also be told what to do
SousChef.prototype.receiveOrder = function(name) {
  console.log(this.name, 'Got it! telling the kitchen to make ' + name);
  this.orders[name].forEach(function(instruction) {
    this.handleOrder(instruction);
  }.bind(this));
};


// the different cooks listen to the SousChef about different things
var Griller = function(name) {
  this.name = name;
  this.chef = terry;
  this.isBusy = false;
  terry.dispatchesOrder('grill', function() {
    console.log(this.name, 'I am grilling!');
    this.isBusy = true;

    setTimeout(function() {
      console.log(this.name, 'Done Grilling');
      this.isBusy = false;
    }.bind(this), 5000);
  }.bind(this));
};

var NoodleCook = function(name) {
  this.name = name;
  this.chef = terry;
 ...