Assistance with implementing the observer pattern in my code

I'm having trouble figuring out what's wrong with my code. The issue pertains to the observer pattern in JavaScript. I keep getting an error that says "Uncaught TypeError: Cannot read property 'push' of undefined". My guess is that this error occurs because the "observers" key is not being created on the object when I use the new keyword.

Js Fiddle: https://jsfiddle.net/2808w5x0/

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

  return {
    subscribeObserver:function(observer){
        observers.push(observer);
    },
    getObservers:function(){return this.observers;},
    unSubscribeObserver:function(observer){
        var index = this.observers.indexof(observer);
      if(index > -1){
        this.observers.splice(index,1);
      }
    },
    notifyObserver:function(observer){
        var index = this.observers.indexof(observer);
      if(index > -1){
        this.observer[index].notify(index);
      }
    },
    notifyAllObserver:function(){
        this.observers.foreach(function(val,idx){
        val.notify(idx);
      });
    }
  };
}

function Observer(){
    return{
    notify:function(idx){
        console.log("Observer " + idx + " notified.");
    }
  }
}

var subject = new Subject();
console.log("subject ",subject.getObservers());
var ob1 = new Observer();
var ob2 = new Observer();
var ob3 = new Observer();
var ob4 = new Observer();

subject.subscribeObserver(ob1);
subject.subscribeObserver(ob2);
subject.subscribeObserver(ob3);
subject.subscribeObserver(ob4);

subject.notifyAllObserver();

Answer №1

When creating a new object with new Subject(), keep in mind that there is an implicit return that provides your new object. Therefore, you do not need to explicitly return the object as you did previously.


To add methods to the object, they should be attached to the prototype of the object. This ensures that when the object is created, it will have those methods already attached to it. For example:

function MySuperObject( value ) {
    this.property = value;
};

MySuperObject.prototype.attachedMethod = function() {
    console.log("Property is equal to : " + this.property) + ".";
};

// Implicit return of the object stored in <myobj>.
var myobj = new MySuperObject(0);

// Result: Property is equal to : 0.
myobj.attachedMethod();

To implement your code correctly:

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

Subject.prototype.subscribeObserver = function( observer ) {
  this.observers.push(observer);
};

Subject.prototype.getObservers = function() {
  return "There are " + this.observers.length + " observers.";
};

function Observer(){
  // ...
}

var subject = new Subject();
console.log("subject ",subject.getObservers());

var ob1 = new Observer();
var ob2 = new Observer();
var ob3 = new Observer();
var ob4 = new Observer();
subject.subscribeObserver(ob1);
subject.subscribeObserver(ob2);
subject.subscribeObserver(ob3);
subject.subscribeObserver(ob4);

// Alternatively:
// for(var i=0; i<4; i++) {
//     subject.subscribeObserver(new Observer());
// }

console.log("subject ",subject.getObservers());

I hope this explanation helps!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Encountering a problem with serializing forms using jQuery

Currently, I am working on form serialization in order to send the file name to the server. However, I have encountered an issue where the serialization values are empty and I am expecting the file name to be included. Within my form, there is an HTML fil ...

When I open my website in a new tab using iOS and Chrome, the appearance of the absolute element is being altered

I am experiencing an issue with a div that is positioned absolutely at the bottom left of my website. When I open the site in a new tab using <a target="_blank" href="./index.html">, the bottom value is not being applied correctly ...

Implementing Ajax/jQuery to simulate HTML form submission via POST method

I am looking to extract and send all post variables along with their content from a form using jquery's "$.post()". Simply doing: $.post("myServer.com/test2.php", $('#myform').serialize()) will not suffice as it would only send one varia ...

Managing errors by employing Scoping Routes via app.use('url','route_file')

1. How can I ensure that my errors are handled by the middleware app.use('/blogs','blogRoutes') which directs my URLs to an API file? 2. Would something like app.use('/blogs','blogRoutes', next){next(err)} be the so ...

Tips for utilizing the search feature in the Blessed list module

Currently, I am working on developing a terminal application using the blessed framework in NodeJS. I am seeking guidance on how to effectively utilize the search functionality within a list component. Can anyone provide detailed instructions or examples? ...

Tips for creating dynamic row styles in a fluid table layout?

Could someone help me figure this out? I'm not familiar with JavaScript and need assistance as I've never created it, only edited existing scripts. I have a layout with two tables side-by-side. On mobile devices, the second table is pushed below ...

Are these two glob patterns distinct from each other in any way?

images/**/*.{png,svg} images/**/*.+(png|svg) After running tests on both expressions, it appears that they generally yield identical outcomes. However, it is crucial to confirm that they are indeed equivalent. ...

Setting up package.json to relocate node_modules to a different directory outside of the web application:

My web app is currently located in C:\Google-drive\vue-app. When I run the command yarn build, it installs a node_modules folder within C:\Google-drive\vue-app. However, since I am using Google Drive to sync my web app source code to Go ...

incapable of modifying the contents of an array

Struggling with a JavaScript issue (not angular related, but within an Angular context) for hours without any success. I've condensed the content into shorter paragraphs and reassigned the subcontent back to the array's content property, but the ...

Adding Information to Flot

I'm struggling to showcase an array of data using a Flot graph. My method involves jQuery Ajax/PHP/MySQL. I created the array with this PHP/MySQL code: $result = mysql_query("SELECT * FROM happiness"); $array = array(); while($row = mysql_fetc ...

How can I execute a function defined in another .js file using JavaScript?

Currently, I am in the process of writing some logic within the fileB.js that requires me to call a function declared in fileA.js. Specifically, fileA.js contains a function named abc(). Could you please advise on how I can successfully call abc() from wit ...

I have implemented a code snippet that verifies if the incoming week aligns with the existing week, triggering an alert accordingly

One of the challenges I faced was checking if a newly created week matched with an existing one, and then displaying an alert. Here's how I approached it: $scope.addWeek = function(type,newWeek,index){ var c = $scope.weekList.length + 1; var ...

How to read a JSON file using Node.js

I need to extract the "name" and "tel" data from data.json (a JSON file) using app.js (node.js file). Below is the content of data.json: { "result": { "site": { "list": [ { "name": "imready", "tel": "0123456789" }, { "nam ...

What is the process for retrieving data from multiple tables within a database using Node.js, MySQL, and Express.js?

Can someone help me pinpoint the issue? I am trying to retrieve data from different MySQL tables using separate queries, specifically in gestionEntreprise.ejs: <tbody> <tr> <% data1.forEach(entry => { %> &l ...

Angular 2: Dynamically Adjusting View Components Based on URL Path

Apologies for the unconventional title. I struggled to come up with a better one. My goal is to develop an application with a simple 3-part structure (header / content / footer). The header should change based on the active route, where each header is a s ...

Getting the document ID from a faunaDb query: a step-by-step guide

One array that I am dealing with consists of the following: [ Ref(Collection("twitch_users"), "280881231730573837") ] My goal is to extract the string of numbers from this array and utilize it in another function within my codebase. Ho ...

Validating forms on the server while using client-side forms in Angular Material

A basic form collects the name and price of a menu item and stores it in a database. A server route is set up to check if the item already exists in the menu. If it does, an error message is sent back through res.json() like this: if (newItem) { //Add ...

"Explore a different approach to file uploading with React Native JavaScript by using either blob or base64 encoding

I am in the process of uploading visuals. When I employ this technique, it functions as expected: formData.append("file",{uri,type,name}); Yet, I prefer not to transmit my visual using the URI. My intention is to divide the visual into distinct sections ...

Enforce the retrieval of all fields, even those that have been overridden

I have a query that utilizes mongoose and involves a select operation. The model's schema is configured to exclude two specific fields, like so: contents: { type: String select: false }, password: { type: String select: false } Howev ...

The process of departing a SocketIO room and switching to a different room logic

I am wondering how I can leave the Room when I click on a new Room Here is what my page looks like: https://i.sstatic.net/vuwv0.png The list on the left side is from the MySQL Server and it displays a list of my chats. Each Room name has an id value whi ...