00001 /* $Id: generic_event.cpp 52533 2012-01-07 02:35:17Z shadowmaster $ */ 00002 /* 00003 Copyright (C) 2006 - 2012 by Joerg Hinrichs <joerg.hinrichs@alice-dsl.de> 00004 Part of the Battle for Wesnoth Project http://www.wesnoth.org/ 00005 00006 This program is free software; you can redistribute it and/or modify 00007 it under the terms of the GNU General Public License as published by 00008 the Free Software Foundation; either version 2 of the License, or 00009 (at your option) any later version. 00010 This program is distributed in the hope that it will be useful, 00011 but WITHOUT ANY WARRANTY. 00012 00013 See the COPYING file for more details. 00014 */ 00015 00016 #include "generic_event.hpp" 00017 00018 #include <algorithm> 00019 00020 namespace events{ 00021 00022 generic_event::generic_event(std::string name) : 00023 name_(name), 00024 observers_(), 00025 change_handler_(false), 00026 notify_active_(false) 00027 { 00028 } 00029 00030 bool generic_event::attach_handler(observer* obs){ 00031 bool handler_attached = false; 00032 00033 //make sure observers are not notified right now 00034 if (!notify_active_){ 00035 change_handler_ = true; 00036 try{ 00037 std::vector<observer*>::const_iterator it = std::find(observers_.begin(), observers_.end(), obs); 00038 if (it != observers_.end()){ 00039 handler_attached = false; 00040 } 00041 else{ 00042 observers_.push_back(obs); 00043 handler_attached = true; 00044 } 00045 } 00046 catch (...){ 00047 change_handler_ = false; 00048 throw; 00049 } 00050 change_handler_ = false; 00051 } 00052 00053 return handler_attached; 00054 } 00055 00056 bool generic_event::detach_handler(observer* obs){ 00057 bool handler_detached = false; 00058 00059 //make sure observers are not notified right now 00060 if (!notify_active_){ 00061 change_handler_ = true; 00062 try{ 00063 std::vector<observer*>::iterator it = std::find(observers_.begin(), observers_.end(), obs); 00064 if (it == observers_.end()){ 00065 handler_detached = false; 00066 } 00067 else{ 00068 observers_.erase(it); 00069 handler_detached = true; 00070 } 00071 } 00072 catch (...){ 00073 change_handler_ = false; 00074 throw; 00075 } 00076 change_handler_ = false; 00077 } 00078 00079 return handler_detached; 00080 } 00081 00082 void generic_event::notify_observers(){ 00083 if (!change_handler_){ 00084 notify_active_ = true; 00085 try{ 00086 for (std::vector<observer*>::const_iterator it = observers_.begin(); 00087 it != observers_.end(); ++it){ 00088 (*it)->handle_generic_event(name_); 00089 } 00090 } 00091 catch (...){ 00092 //reset the flag if event handlers throw exceptions and don't catch them 00093 notify_active_ = false; 00094 throw; 00095 } 00096 notify_active_ = false; 00097 } 00098 } 00099 00100 } //namespace events
| Generated by doxygen 1.7.1 on Fri May 25 2012 01:02:53 for The Battle for Wesnoth | Gna! | Forum | Wiki | CIA | devdocs |