1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim: set ts=8 sts=2 et sw=2 tw=80: */
3 /* This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
7 #ifndef mozilla_Observer_h
8 #define mozilla_Observer_h
10 #include "nsTObserverArray.h"
15 * Observer<T> provides a way for a class to observe something.
16 * When an event has to be broadcasted to all Observer<T>, Notify() method
18 * T represents the type of the object passed in argument to Notify().
25 virtual ~Observer() = default;
26 virtual void Notify(const T
& aParam
) = 0;
30 * ObserverList<T> tracks Observer<T> and can notify them when Broadcast() is
32 * T represents the type of the object passed in argument to Broadcast() and
33 * sent to Observer<T> objects through Notify().
41 * Note: When calling AddObserver, it's up to the caller to make sure the
42 * object isn't going to be release as long as RemoveObserver hasn't been
45 * @see RemoveObserver()
47 void AddObserver(Observer
<T
>* aObserver
) {
48 mObservers
.AppendElementUnlessExists(aObserver
);
52 * Remove the observer from the observer list.
53 * @return Whether the observer has been found in the list.
55 bool RemoveObserver(Observer
<T
>* aObserver
) {
56 return mObservers
.RemoveElement(aObserver
);
59 uint32_t Length() { return mObservers
.Length(); }
62 * Call Notify() on each item in the list.
64 void Broadcast(const T
& aParam
) {
65 for (Observer
<T
>* obs
: mObservers
.ForwardRange()) {
71 nsTObserverArray
<Observer
<T
>*> mObservers
;
74 } // namespace mozilla
76 #endif // mozilla_Observer_h