Tutorials  /  JavaScript

JavaScript: The Observer Design Pattern

Ccentron Redaktion · November 2023 ·3 min read ·JavaScript, Tutorial

Dependent components can be informed about changes in an object in JavaScript using the Observer Design Pattern. We'll show you two possible approaches.

The Observer Design Pattern in Software Development

The Observer Design Pattern is a crucial approach in software development to communicate changes in one part of the application to other parts. For example, in AngularJS, the $scope object can trigger changes, thus notifying other components. This pattern allows informing dependent objects about changes. Another example is the Model-View-Controller (MVC) architecture, where the view updates when the model changes. A significant advantage of this pattern is decoupling the view from the models and reducing dependencies.

Key Components of the Observer Design Pattern

In the Observer Design Pattern, there are three key components: the subject (the observed object), the observer, and concrete observer objects. The subject contains references to concrete observers to notify them of changes. The observer object is an abstract class that enables concrete observers to implement the notification method (notify).

Example in AngularJS

Code
// Controller 1
$scope.$on('nameChanged', function(event, args) {
    $scope.name = args.name;
});

// ...

// Controller 2
$scope.userNameChanged = function(name) {
    $scope.$emit('nameChanged', {name: name});
};

Here, changes in the name are triggered using the $emit event and caught by other controllers.

Implementing Your Own Subjects and Observers

JavaScript
var Subject = function() {
    this.observers = [];

    return {
        subscribeObserver: function(observer) {
            this.observers.push(observer);
        },
        // Other methods: unsubscribeObserver, notifyObserver, notifyAllObservers
    };
};

var Observer = function() {
    return {
        notify: function(index) {
            console.log("Observer " + index + " is notified!");
        }
    };
}
VM

Matching infrastructure at centron

Node applications need somewhere to run: ccloud³ VMs with full root access from €3.12 per month – or as a managed server if you would rather not run it yourself. Rent a cloud server →

Publish/Subscribe as an Alternative

The Publish/Subscribe pattern is an alternative method in which there is a topic/event channel between objects that want to receive notifications (subscribers) and the object that triggers the event (publisher). This system allows defining application-specific events that can carry custom arguments. Unlike the Observer pattern, in the Publish/Subscribe pattern, each subscriber implements an appropriate event handler to subscribe to and receive topic notifications from the publisher.

In AngularJS, subscribers can subscribe to events using $on('event', callback), and publishers use $emit('event', args) or $broadcast('event', args`) to trigger events.

It's essential to note that the Observer Design Pattern offers many advantages but also has drawbacks, such as performance issues, especially with a large number of observers. Therefore, the choice between Observer and Publish/Subscribe should be made based on the project's requirements and complexity. Understanding the Observer Design Pattern in JavaScript

Jetzt 200 € Guthaben sichern

Testen Sie Ihr Setup auf ccloud³

Registrieren Sie sich in der ccloud³ und erhalten Sie 200 € Startguthaben für Ihr Projekt – z. B. für eine PostgreSQL-VM mit automatischen Backups.

centron Redaktion Technische Redaktion

Das Redaktionsteam von centron schreibt Anleitungen aus dem Betriebsalltag: getestet auf unserer eigenen Plattform, betrieben im Rechenzentrum in Hallstadt bei Bamberg.

Kategorie JavaScript
Teilen
Noch offene Fragen?

Our team will help you with your specific setup - in German or English, by people who run the platform themselves.

War dieses Tutorial hilfreich?

Your answer is stored anonymously and helps us improve our tutorials.

Kommentare

No comments yet - be the first to ask a question about this tutorial.

Sign in to comment

Comments are open to centron customers. Sign in to your account to ask a question about this tutorial.

Weiterlesen

Das könnte Sie auch interessieren

Jetzt kostenlos anfangen

Melden Sie sich an und erhalten Sie in den ersten 60 Tagen ein Guthaben von 200 € bei centron.

Dieses Werbeangebot gilt nur für neue Konten. Angebot ausschließlich für Gewerbetreibende.

Jetzt loslegen Sales kontaktieren