Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URLs added here will be added as <link>s in order, and before the CSS in the editor. You can use the CSS from another Pen by using its URL and the proper URL extension.

+ add another resource

JavaScript

Babel includes JSX processing.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

Auto Save

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                <!doctype html>
<html lang="en">

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
    integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

  <title>Observer Design Pattern</title>
</head>

<body>
  <div class="container-fluid">
    <br>
    <h2>Observer Design Pattern </h2>
    <div class="row">
      <div class="col-md-2">
        <br>
        <!-- Populated by HtmlCustomElement -->
        <div class="card p-2 text-center" style="color: white;" id="HtmlObserver1"></div>
        <br>
        <div>
          <button onclick="subject.OnNext();" type="button" class="btn btn-primary">Next</button>
        </div>
        <br>
        <div>
          <button onclick="OnDetachHistory();" type="button" class="btn btn-danger">Detach History</button>
        </div>
        
        <!-- Subject -->
        <script src="js/subject/CardSubject.js" charset="utf-8"></script>
        
        <!-- Observers -->
        <script src="js/observers/HtmlObserver.js" charset="utf-8"></script>
        <script src="js/observers/ColorLogObserver.js" charset="utf-8"></script>
        <script src="js/observers/ColorHistoryObserver.js" charset="utf-8"></script>
        
        <!-- Main Function -->
        <script src="js/Client.js" charset="utf-8"></script>
      
      </div>
    </div>
  </div>

  <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"
    integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo"
    crossorigin="anonymous"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"
    integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1"
    crossorigin="anonymous"></script>
  <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"
    integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM"
    crossorigin="anonymous"></script>
</body>

</html>
              
            
!

CSS

              
                
              
            
!

JS

              
                class ColorHistoryObserver {
  constructor() {
    this.colorHistory = [];
  }

  //Update method for this Observer
  update(subject) {
    this.colorHistory.unshift(subject.color);

    let msg = 'History :';
    for (let i = 0; i < 3; i++) {
      if (!this.colorHistory[i]) continue;
      msg += '\n ' + this.colorHistory[i] ;
    }

    console.log(msg);
  }
}


class ColorLogObserver {
  constructor() { }

  //Update method for this Observer
  update(subject) {
    
    //Output based on subject current state
    console.log(
      `%c ${subject.counter}) ${subject.color.toUpperCase()}`,
      `color:${subject.color}`
    );
  }
}

class HtmlObserver {
  constructor(elementId) {
    this.element = document.getElementById(elementId);
  }

  //Update method for this Observer
  update(subject) {
    
    //Set the state for this observer
    this.element.style.backgroundColor = subject.color; //set the background color 
    this.element.innerHTML = subject.counter; //inject the number into the html element
  }
}

const COLORS = ['purple', 'black', 'red', 'blue', 'green'];

/** CardSubject : Subject Concrete implementation
 * 
 *  subscribe: attach an Observer
 *  unsubscribe: detach an Observer
 *  notify: notify to all observers
 * 
 *  OnNext: Listener attached to the html button element
 * */
class CardSubject {
  constructor() {
    this.observers = [];
    this.counter = 0; // start counting from 0
    this.color = "purple"; // default color
  }

  //SUBSCRIBE
  subscribe(o) {
    this.observers.push(o);
  }

  //UNSUBSCRIBE
  unSubscribe(obsToRemove) {
    this.observers = this.observers.filter(obs => {
      if (obs != obsToRemove) {
        return obs
      }
    });
    console.warn("unsubscribed: ", obsToRemove);
  }

  //NOTIFY
  notify() {
    for (const o of this.observers) {
      o.update(this);
    }
  }

  //Implementation of the logic for state change on this subject
  setState() {
    this.counter++;
    this.color = COLORS[Math.floor(Math.random() * COLORS.length)]
  }

  OnNext() {
    this.setState(); // Set new State for this subjet
    this.notify(); // Notify changes to all observables subscribed
  }
}

//New concrete Subject instance
const subject = new CardSubject();

//New concrete Observers
const obs1 = new ColorLogObserver();
const obs2 = new HtmlObserver('HtmlObserver1')
const obs3 = new ColorHistoryObserver();

//Attach Observers
subject.subscribe(obs1);
subject.subscribe(obs2);
subject.subscribe(obs3);

OnDetachHistory = () => {
  subject.unSubscribe(obs3);
}

// Notify
subject.notify();



              
            
!
999px

Console