Last active
February 13, 2024 09:37
-
-
Save materkel/124632885680f3aa91873a79455f8ee2 to your computer and use it in GitHub Desktop.
Basic Event Emitter in Zig 0.11
This file contains hidden or 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
const std = @import("std"); | |
const String = []const u8; | |
const ListenersList = std.ArrayList(*const fn(String) void); | |
pub const EventEmitter = struct { | |
allocator: *std.mem.Allocator, | |
listeners: std.StringHashMap(*ListenersList), | |
pub fn init(allocator: *std.mem.Allocator) EventEmitter { | |
return EventEmitter{ | |
.allocator = allocator, | |
.listeners = std.StringHashMap(*ListenersList).init(allocator.*) | |
}; | |
} | |
pub fn on(self: *EventEmitter, event_type: String, listener: *const fn(String) void) void { | |
var maybe_listeners = self.listeners.get(event_type); | |
if (maybe_listeners) |listeners| { | |
listeners.append(listener) catch unreachable; | |
} else { | |
var newList = self.allocator.create(ListenersList) catch unreachable; | |
newList.* = ListenersList.init(self.allocator.*); | |
newList.append(listener) catch unreachable; | |
self.listeners.put(event_type, newList) catch unreachable; | |
} | |
} | |
pub fn emit(self: EventEmitter, event_type: String, event_value: String) void { | |
var maybe_listeners = self.listeners.get(event_type); | |
if (maybe_listeners) |listeners| { | |
for (listeners.items) |listener| { | |
listener(event_value); | |
} | |
} | |
} | |
}; |
This file contains hidden or 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
const std = @import("std"); | |
const Allocator = std.mem.Allocator; | |
const EventEmitter = @import("./EventEmitter.zig").EventEmitter; | |
const String = []const u8; | |
pub fn main() !void { | |
var general_purpose_allocator = std.heap.GeneralPurposeAllocator(.{}){}; | |
var gpa = general_purpose_allocator.allocator(); | |
var arena = std.heap.ArenaAllocator.init(gpa); | |
defer arena.deinit(); | |
var allocator = arena.allocator(); | |
var event_emitter = EventEmitter.init(&allocator); | |
event_emitter.on("yo", &handleEvent); | |
event_emitter.emit("yo", "event string value"); | |
} | |
fn handleEvent(event: String) void { | |
const stdout = std.io.getStdOut().writer(); | |
stdout.print("Received, {s}\n", .{event}) catch unreachable; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment