-
-
Notifications
You must be signed in to change notification settings - Fork 25
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
ce2292e
commit 1eca7b4
Showing
2 changed files
with
49 additions
and
34 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,49 @@ | ||
// | ||
// EventManager.swift | ||
// Mythic | ||
// | ||
// Created by Esiayo Alegbe on 21/11/2023. | ||
// | ||
|
||
import Foundation | ||
|
||
// A class that allows for cross-script variables and communication | ||
// Example usage: | ||
/* | ||
EventManager.shared.subscribe("test") { data in | ||
if let value = data as? String { | ||
print("chat is this \(value)") | ||
|
||
} | ||
} | ||
|
||
EventManager.shared.publish("test", "real?") | ||
*/ | ||
|
||
/// Allows for cross-script communication via subscribeable events | ||
class EventManager { | ||
/// The shared instance for events | ||
static let shared = EventManager() | ||
|
||
/// Event storage | ||
private var events = [String: [(Any) -> Void]]() | ||
|
||
/// Subscribe to events within the event manager | ||
/// - Parameter event: The event to subscribe to. | ||
public func subscribe(_ event: String, _ callback: @escaping (Any) -> Void) { | ||
if events[event] == nil { | ||
events[event] = Array() | ||
} | ||
events[event]?.append(callback) | ||
} | ||
|
||
/// Publish new values to events | ||
/// - | ||
public func publish(_ event: String, _ data: Any) { | ||
if let callbacks = events[event] { | ||
for callback in callbacks { | ||
callback(data) | ||
} | ||
} | ||
} | ||
} |