فهرست منبع

Invader sample: Clean up event listeners, see #605

Michael Ragazzon 1 سال پیش
والد
کامیت
386820b24e

+ 12 - 0
Samples/invaders/src/ElementGame.cpp

@@ -100,3 +100,15 @@ void ElementGame::OnChildAdd(Rml::Element* element)
 		GetOwnerDocument()->AddEventListener(Rml::EventId::Keyup, this);
 	}
 }
+
+void ElementGame::OnChildRemove(Rml::Element* element)
+{
+	Rml::Element::OnChildRemove(element);
+
+	if (element == this)
+	{
+		GetOwnerDocument()->RemoveEventListener(Rml::EventId::Load, this);
+		GetOwnerDocument()->RemoveEventListener(Rml::EventId::Keydown, this);
+		GetOwnerDocument()->RemoveEventListener(Rml::EventId::Keyup, this);
+	}
+}

+ 4 - 3
Samples/invaders/src/ElementGame.h

@@ -46,11 +46,12 @@ public:
 	/// Intercepts and handles key events.
 	void ProcessEvent(Rml::Event& event) override;
 
-	/// Receive notifications when child elements are added
-	/// This will only get called when we're added to the tree,
-	/// which allows us to bind to onload
+	/// This will get called when we're added to the tree, which allows us to bind to events.
 	void OnChildAdd(Rml::Element* element) override;
 
+	/// This will get called when we're removed from the tree, which allows us to clean up the event listeners previously added.
+	void OnChildRemove(Element* element) override;
+
 protected:
 	/// Updates the game.
 	void OnUpdate() override;

+ 12 - 0
Samples/luainvaders/src/ElementGame.cpp

@@ -103,3 +103,15 @@ void ElementGame::OnChildAdd(Rml::Element* element)
 		GetOwnerDocument()->AddEventListener(Rml::EventId::Keyup, this);
 	}
 }
+
+void ElementGame::OnChildRemove(Rml::Element* element)
+{
+	Rml::Element::OnChildRemove(element);
+
+	if (element == this)
+	{
+		GetOwnerDocument()->RemoveEventListener(Rml::EventId::Load, this);
+		GetOwnerDocument()->RemoveEventListener(Rml::EventId::Keydown, this);
+		GetOwnerDocument()->RemoveEventListener(Rml::EventId::Keyup, this);
+	}
+}

+ 4 - 3
Samples/luainvaders/src/ElementGame.h

@@ -46,11 +46,12 @@ public:
 	/// Intercepts and handles key events.
 	void ProcessEvent(Rml::Event& event) override;
 
-	/// Receive notifications when child elements are added
-	/// This will only get called when we're added to the tree,
-	/// which allows us to bind to onload
+	/// This will get called when we're added to the tree, which allows us to bind to events.
 	void OnChildAdd(Rml::Element* element) override;
 
+	/// This will get called when we're removed from the tree, which allows us to clean up the event listeners previously added.
+	void OnChildRemove(Element* element) override;
+
 protected:
 	/// Updates the game.
 	void OnUpdate() override;