no bug - Bumping Firefox l10n changesets r=release a=l10n-bump DONTBUILD CLOSED TREE
[gecko.git] / xpcom / ds / Observer.h
blob3d189603eb6dd5285f8f13dcdb4b0c3befeb9719
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"
12 namespace mozilla {
14 /**
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
17 * is called.
18 * T represents the type of the object passed in argument to Notify().
20 * @see ObserverList.
22 template <class T>
23 class Observer {
24 public:
25 virtual ~Observer() = default;
26 virtual void Notify(const T& aParam) = 0;
29 /**
30 * ObserverList<T> tracks Observer<T> and can notify them when Broadcast() is
31 * called.
32 * T represents the type of the object passed in argument to Broadcast() and
33 * sent to Observer<T> objects through Notify().
35 * @see Observer.
37 template <class T>
38 class ObserverList {
39 public:
40 /**
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
43 * called.
45 * @see RemoveObserver()
47 void AddObserver(Observer<T>* aObserver) {
48 mObservers.AppendElementUnlessExists(aObserver);
51 /**
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(); }
61 /**
62 * Call Notify() on each item in the list.
64 void Broadcast(const T& aParam) {
65 for (Observer<T>* obs : mObservers.ForwardRange()) {
66 obs->Notify(aParam);
70 protected:
71 nsTObserverArray<Observer<T>*> mObservers;
74 } // namespace mozilla
76 #endif // mozilla_Observer_h