softwarecontainer  0.18.0-739e8d7 2017-05-04
observableproperty.h
1 /*
2  * Copyright (C) 2016-2017 Pelagicore AB
3  *
4  * Permission to use, copy, modify, and/or distribute this software for
5  * any purpose with or without fee is hereby granted, provided that the
6  * above copyright notice and this permission notice appear in all copies.
7  *
8  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
9  * WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
10  * WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR
11  * BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES
12  * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
13  * WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
14  * ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
15  * SOFTWARE.
16  *
17  * For further information see LICENSE
18  */
19 
20 #include <functional>
21 #include <vector>
22 
23 template<typename Type>
25 {
26 public:
27  typedef std::function<void (const Type &)> Listener;
28 
29  ObservableProperty(Type &value) :
30  m_value(value)
31  {
32  }
33 
34  void addListener(Listener listener)
35  {
36  m_listeners.push_back(listener);
37  }
38 
39  operator const Type &() {
40  return m_value;
41  }
42 
43 protected:
44  std::vector<Listener> m_listeners;
45 
46 private:
47  const Type &m_value;
48 
49 };
50 
51 template<typename Type>
53  public ObservableProperty<Type>
54 {
55 public:
56  ObservableWritableProperty(Type value) :
57  ObservableProperty<Type>(m_value), m_value(value)
58  {
59  }
60 
63  {
64  }
65 
66  void setValueNotify(Type value)
67  {
68  m_value = value;
69  for (auto &listener : ObservableProperty<Type>::m_listeners) {
70  listener(getValue());
71  }
72  }
73 
74  const Type &getValue() const
75  {
76  return m_value;
77  }
78 
79  ObservableWritableProperty &operator=(const Type &type)
80  {
81  m_value = type;
82  return *this;
83  }
84 
85 
86 private:
87  Type m_value;
88 
89 };
90