jeudi 13 avril 2017

ES5 Observer Pattern

I am trying to learn about design patterns so I am implementing the observer pattern in ES5.

This is what my code looks like.

function Subject() {}
Subject.prototype.subscribe = function(newObserver) {
  this.observers.push(newObserver);
};
Subject.prototype.unsubscribe = function(removeObserver) {
  this.observers = this.observers.filter(function(observer) {
    return removeObserver !== observer;
  });
};
Subject.prototype.updateSubscribers = function() {
  this.observers.forEach(function(observer) {
    observer.update(this.isChecked);
  });
};

function CheckboxSubject() {
  this.observers = [];
  this.isChecked = false;
}
CheckboxSubject.prototype = Object.create(Subject.prototype, {
  check: {
    value: function() {
      this.isChecked = !this.isChecked;
      console.log(this.isChecked);
      this.updateSubscribers();
    },
  },
});
CheckboxSubject.prototype.constructor = CheckboxSubject;

function Observer() {}
Observer.prototype.update = function() {
  throw new Error('Observer.update() is abstract');
};

function TextFieldObserver() {}
TextFieldObserver.prototype = Object.create(Observer.prototype, {
  update: {
    value: function(updatedState) {
      console.log('New State: ' + updatedState);
    },
  },
});
TextFieldObserver.prototype.constructor = TextFieldObserver;

var checkbox = new CheckboxSubject();
var textField = new TextFieldObserver();
checkbox.subscribe(textField);
checkbox.check();

When I run this code on the Node.js command line it logs this.isChecked as undefined.

I think it has to do with the fact that I am using this.isChecked in the Subject class although it is a property of the CheckboxSubject but I can not wrap my head around how to fix this. I already tried binding the context in vaious ways with .bind() or something similar but nothing worked.

How do I need to adjust this so that whenever I call .check() it outputs the current value of isChecked?

Aucun commentaire:

Enregistrer un commentaire