-
Notifications
You must be signed in to change notification settings - Fork 24
Open
Description
Iโm not 100% sure I dug out the very core issue here, but I put a sufficiently minimal repro in a gist, which will hopefully help analyze the bug.
I import a function which takes a string
as a parameter, which is working fine with as-bind
. However, some of my functions rely on this
being the object the imported function is defined on. So I thought Iโd bind()
all functions before importing. as-bind
handles that, too. Then I thought I should do the binding lazily, so I added a Proxy
that does the binding on GET
and caches it in a Map
. Now, as-bind
is failing to do its job and I just get a pointer.
import { AsBind } from "as-bind";
// Bundler magic compiles my ASC for me
import wasmUrl from "asc:./main.ts";
// Manually binds all methods found on `obj` to `obj.
function manualbind(obj) {
const returnobj = {};
for (const key of Object.keys(obj)) {
if (typeof obj[key] === "function") {
returnobj[key] = obj[key].bind(obj);
}
returnobj[key] = obj[key];
}
return returnobj;
}
// *Lazily* binds all methods found on `obj` to `obj.
function proxybind(obj) {
const bindCache = new Map();
return new Proxy(obj, {
get(target, p) {
if (bindCache.has(p)) {
return bindCache.get(p);
}
if (typeof target?.[p] === "function") {
const bound = target[p].bind(target);
bindCache.set(p, bound);
return bound;
}
return target[p];
},
});
}
function myalert(s) {
alert(`message: ${JSON.stringify(s)}, has a this: ${this !== null}`);
}
async function main() {
// Works fine!
const instance = await AsBind.instantiate(fetch(wasmUrl), {
main: { myalert },
});
instance.exports.run("vanilla");
// Works fine!
const instance2 = await AsBind.instantiate(fetch(wasmUrl), {
main: manualbind({ myalert }),
});
instance2.exports.run("manualbind");
// Breaks. I only get a pointer value and not the string.
const instance3 = await AsBind.instantiate(fetch(wasmUrl), {
main: proxybind({ myalert }),
});
instance3.exports.run("proxybind");
}
main();
Can you take a look and let me know if itโs something that I am doing wrong or something we can fix in as-bind
?
Metadata
Metadata
Assignees
Labels
No labels