Search code examples
javascriptdebuggingdesign-patternsobserver-patternobservers

Trouble running an Observer Pattern example


I am trying to reproduce the Observer Pattern example given in the book Learning JavaScript Design Patterns but I get this error in the extend function:

enter image description here

I am using the code in the book starting below this line:

First, let's model the list of dependent Observers a subject may have:

I have set up the code in a fiddle and I'd like to understand why I'm getting the error.


Solution

  • The issue in the reported error in your question is that the first argument to extend() is not a valid object.

    When I run your jsFiddle, it reports that Observer is not defined.

    If the Observer() pattern should be parallel to the Subject() pattern, then you are missing this piece of code:

    function Observer() {
      this.observers = new ObserverList();
    }
    

    Or, perhaps you just need to change:

    extend( new Observer(), check );
    

    to:

    extend( new ObserverList(), check );
    

    So that it uses the code you show for ObserverList().


    In fact, when I press the button in your jsFiddle, the error that occurs is Uncaught ReferenceError: Observer is not defined which further confirms the above.

    And, when I apply that change, the code seems to run here: http://jsfiddle.net/jfriend00/8xmu1mcg/, though I don't know exactly what it's supposed to do, but it adds a checkbox and there are no errors.