Design Patterns
  • Introduction
  • Proto-Pattern
  • Anti-pattern
  • OO Design Principles
  • Classification
  • Creational Design Patterns
    • Singleton
    • Factory
    • Abstract Factory
    • Builder
    • Prototype
  • Structural design patterns
    • Adapter
    • Bridge
    • Composite
    • Decorator
    • Facade
    • Flyweight
    • Proxy
  • Behavioural Design Pattern
    • Chain of Responsibility
    • Command
    • Interpreter
    • Iterator
    • Mediator
    • Memento
    • Observer
    • State
    • Strategy
    • Template Method
    • Visitor
  • Concurrency Design Pattern
  • Architectural Design Pattern
  • Modern Desing Patterns
Powered by GitBook
On this page

Was this helpful?

  1. Behavioural Design Pattern

Observer

A way of notifying change to a number of classes.

  • The Observer pattern offers a subscription model in which objects subscribe to an event and get notified when the event occurs.

  • This pattern is the cornerstone of event driven programming, including JavaScript.

  • The Observer pattern facilitates good object-oriented design and promotes loose coupling.

  • When building web apps you end up writing many event handlers. Event handlers are functions that will be notified when a certain event fires.

  • These notifications optionally receive an event argument with details about the event.

EX:
function Click() {
    this.handlers = [];  // observers
}
 
Click.prototype = {
 
    subscribe: function(fn) {
        this.handlers.push(fn);
    },
 
    unsubscribe: function(fn) {
        this.handlers = this.handlers.filter(
            function(item) {
                if (item !== fn) {
                    return item;
                }
            }
        );
    },
 
    fire: function(o, thisObj) {
        var scope = thisObj || window;
        this.handlers.forEach(function(item) {
            item.call(scope, o);
        });
    }
}

function run() { 
    var clickHandler = function(item) { 
        console.log("fired: " + item); 
    }; 
    var click = new Click(); 
    click.subscribe(clickHandler);
    click.fire('event #1');
    click.unsubscribe(clickHandler);
    click.fire('event #2');
    click.subscribe(clickHandler);
    click.fire('event #3');

}

run();
PreviousMementoNextState

Last updated 5 years ago

Was this helpful?