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.11 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

Claim €200 credit

Test your setup on ccloud³

Sign up for ccloud³ and receive €200 starting credit for your project.

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.

Get started for free

Sign up and receive €200 credit at centron within your first 60 days.

This promotional offer applies to new accounts only. Available exclusively to businesses.