Skip to content

Instantly share code, notes, and snippets.

@surma

surma/.gitignore Secret

Created March 6, 2021 17:35
Show Gist options
  • Save surma/7cc043d26c56915a37dd79110e5d783c to your computer and use it in GitHub Desktop.
Save surma/7cc043d26c56915a37dd79110e5d783c to your computer and use it in GitHub Desktop.
asdf
node_modules
package-lock.json
dist
$ npm install
$ npm start
<!DOCTYPE html>
<script src="./dist/main.js" type="module"></script>
import { AsBind } from "as-bind";
import wasmUrl from "asc:./main.ts";
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;
}
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() {
const instance = await AsBind.instantiate(fetch(wasmUrl), {
main: { myalert },
});
instance.exports.run("vanilla");
const instance2 = await AsBind.instantiate(fetch(wasmUrl), {
main: proxybind({ myalert }),
});
instance2.exports.run("proxybind");
const instance3 = await AsBind.instantiate(fetch(wasmUrl), {
main: manualbind({ myalert }),
});
instance3.exports.run("manualbind");
}
main();
declare function myalert(str: string): void;
export function run(str: string): void {
myalert(str);
}
{
"name": "asbindbug",
"version": "0.0.1",
"description": "",
"main": "index.js",
"scripts": {
"start": "rollup -c && serve ."
},
"keywords": [],
"author": "Surma <surma@surma.dev>",
"license": "Apache-2.0",
"dependencies": {
"@rollup/plugin-node-resolve": "^11.2.0",
"as-bind": "^0.6.1",
"assemblyscript": "^0.18.12",
"rollup": "^2.40.0",
"rollup-plugin-assemblyscript": "^2.0.0"
},
"devDependencies": {
"serve": "^11.3.2"
}
}
import nodeResolve from "@rollup/plugin-node-resolve";
import { asc } from "rollup-plugin-assemblyscript";
export default {
input: "main.js",
output: {
dir: "dist",
format: "esm",
},
plugins: [
nodeResolve(),
asc({
useAsBind: true,
}),
],
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment