dispatch events with proper this

This commit is contained in:
Karl Seguin
2026-01-07 17:57:34 +08:00
parent 39874137d6
commit dab6345885
3 changed files with 12 additions and 24 deletions

View File

@@ -186,7 +186,7 @@ pub fn dispatchWithFunction(self: *EventManager, target: *EventTarget, event: *E
if (function_) |func| {
event._current_target = target;
if (func.call(void, .{event})) {
if (func.callWithThis(void, target, .{event})) {
was_dispatched = true;
} else |err| {
// a non-JS error
@@ -349,7 +349,7 @@ fn dispatchPhase(self: *EventManager, list: *std.DoublyLinkedList, current_targe
}
switch (listener.function) {
.value => |value| try value.call(void, .{event}),
.value => |value| try value.callWithThis(void, current_target, .{event}),
.string => |string| {
const str = try page.call_arena.dupeZ(u8, string.str());
try self.page.js.eval(str, null);

View File

@@ -203,27 +203,6 @@ fn trackCallback(self: *Context, pf: PersistentFunction) !void {
return self.callbacks.append(self.arena, pf);
}
// Given an anytype, turns it into a v8.Object. The anytype could be:
// 1 - A V8.object already
// 2 - Our js.Object wrapper around a V8.Object
// 3 - A zig instance that has previously been given to V8
// (i.e., the value has to be known to the executor)
pub fn valueToExistingObject(self: *const Context, value: anytype) !v8.Object {
if (@TypeOf(value) == v8.Object) {
return value;
}
if (@TypeOf(value) == js.Object) {
return value.js_obj;
}
const persistent_object = self.identity_map.get(@intFromPtr(value)) orelse {
return error.InvalidThisForCallback;
};
return persistent_object.castToObject();
}
// == Executors ==
pub fn eval(self: *Context, src: []const u8, name: ?[]const u8) !void {
_ = try self.exec(src, name);

View File

@@ -129,7 +129,16 @@ pub fn callWithThis(self: *const Function, comptime T: type, this: anytype, args
context.call_depth = call_depth + 1;
defer context.call_depth = call_depth;
const js_this = try context.valueToExistingObject(this);
const js_this = blk: {
if (@TypeOf(this) == v8.Object) {
break :blk this;
}
if (@TypeOf(this) == js.Object) {
break :blk this.js_obj;
}
break :blk try context.zigValueToJs(this, .{});
};
const aargs = if (comptime @typeInfo(@TypeOf(args)) == .null) struct {}{} else args;