Skip to content

Instantly share code, notes, and snippets.

@sortofsleepy
Created May 30, 2020 15:07
Show Gist options
  • Select an option

  • Save sortofsleepy/3c976648b3883dfef3568b8b5e44557f to your computer and use it in GitHub Desktop.

Select an option

Save sortofsleepy/3c976648b3883dfef3568b8b5e44557f to your computer and use it in GitHub Desktop.
Example of how to deal with HTML elements and callbacks entirely in Emscripten/C++.
/*
I know I pieced this together largely from another person's idea and their goal of trying to deal with
XMLHTTPRequests. I unfortunately can't find the original source, if you happen to be that person and this looks
familiar, link me to your post(s) and I'll credit you properly
*/
// Somewhere in your .cpp file "EmscriptenCallback" and "Callback" can be whatever you want, it just has to be a unique name
// for the argument to the std::function, that can be whatever you want too but for the purposes of this i think it makes sense to
// leave it as a val since you're expecting an event object back.
EMSCRIPTEN_BINDINGS( EmscriptenCallback ) {
emscripten::class_<std::function<void( emscripten::val e )> >( "Callback" )
.constructor<>()
.function( "onload", &std::function<void( emscripten::val e )>::operator());
};
auto fun = emscripten::val( onDrop )[ "onload" ].call<emscripten::val>( "bind", emscripten::val(<your std::function>) );
// imagine this is already assigned to an element on the DOM
emscripten::val el;
// call set with the event name and your function.
el.set( "ondrop" , fun);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment