---
# System prepended metadata

title: Observer pattern

---

# Observer pattern

The observer pattern is a software design pattern in which an object, called the subject, maintains a list of its dependents, called observers, and notifies them automatically of any state changes, usually by calling one of their methods https://en.wikipedia.org/wiki/Observer_pattern


Your missing, should you accept it, is to build the `observe` library.

## API
You can require the library like this

```
const Observe = require('observe')
```

### Initialization
We get the `observer`. This is the object that is now observing changes on it's underlying data.
It can be an object, string, or just anything
```
variableToObserve = 1
observer = Observe(variableToObserve)

// you can also initialize it in placce. e.g
// observer = Observe(1)
```

### Attaching listeners
This function is defined by the user of the observe library. 
So he knows how he wants to handle the changes.
The event object should have all necessary properties. The `caller`, `oldValue`, `newValue`, etc..
In this case, we just want to print that something has changed.
```
function listener(event) {
    console.log('somthing has changed', event)
}
```

Now attach a listener that will be called or triggered when the observing data changes.
```
observer.attach(listener)

// its possible to attach several listeners at once
// observer.attach(listener1)
// observer.attach(listener2)

// If you like, you can make attach function to take multiple listeners at once. 
// observer.attach(a,b,c...)
```

### Useful methods
The observer also exposes a `getter` and `setter`
```
currentVal = observer.get() // 1
observer.set(3); // We expect listen() function to be called.
currentVal = observer.get() // 3
```

If you don't want to observe again, you can detach a listener
```
observer.detach(listener);
// As with attach, you can also make it to detach several listeners at once. observer.detach(a,b,c...)
```

If you like, you can also add nice helper methods to observer. e.g
```
observer.listeners() // returns a list of all listeners
observer.detachAll() // detaches all listerns
etc..
```

### Bonus
Write unit tests :)
___

**Note: changing the original variable directly as in: `variableToObserve = 5` for example, does not trigger anything. Its just a normal variable.
You must pass through the `observer` to trigger updates.**