Skip to content

Instantly share code, notes, and snippets.

@adamjs
Created December 3, 2019 06:50
Show Gist options
  • Save adamjs/d689ad6d291a1cdd4e923c63a66cc22d to your computer and use it in GitHub Desktop.
Save adamjs/d689ad6d291a1cdd4e923c63a66cc22d to your computer and use it in GitHub Desktop.
Testing JavaScript Promises with Ultralight 1.1
#include <AppCore/App.h>
#include <AppCore/Window.h>
#include <AppCore/Overlay.h>
#include <AppCore/JSHelpers.h>
using namespace ultralight;
const char* htmlString();
class MyApp : public LoadListener {
RefPtr<Overlay> overlay_;
public:
MyApp(Ref<Window> win) {
overlay_ = Overlay::Create(win, win->width(), win->height(), 0, 0);
overlay_->view()->set_load_listener(this);
overlay_->view()->LoadHTML(htmlString());
}
virtual ~MyApp() {}
JSValue GetMessage(const JSObject& thisObject, const JSArgs& args) {
if (args.size() == 3) {
JSValue obj = args[0];
JSValue resolve = args[1];
JSValue reject = args[2];
if (resolve.IsFunction()) {
JSFunction resolveFunc = resolve.ToFunction();
resolveFunc({ "Hello!" });
}
}
return JSValue();
}
virtual void OnDOMReady(ultralight::View* caller) {
SetJSContext(caller->js_context());
JSObject global = JSGlobalObject();
global["GetMessage"] = BindJSCallbackWithRetval(&MyApp::GetMessage);
}
};
int main() {
auto app = App::Create();
auto window = Window::Create(app->main_monitor(), 300, 300, false, kWindowFlags_Titled);
window->SetTitle("Testing JavaScript Promises");
app->set_window(window);
MyApp my_app(window);
app->Run();
return 0;
}
const char* htmlString() {
return R"(
<html>
<head>
<style type="text/css">
body {
font-family: -apple-system, 'Segoe UI', Ubuntu, Arial, sans-serif;
text-align: center;
background: linear-gradient(#FFF, #DDD);
padding: 2em;
}
#message {
padding-top: 2em;
color: black;
font-weight: bold;
font-size: 24px;
}
</style>
<script type="text/javascript">
function HandleButton(evt) {
var obj = { someJson:2 };
return new Promise(function(resolve, reject) {
GetMessage(obj, resolve, reject)
}).then(function(message) {
// Display the result in our 'message' div element
document.getElementById('message').innerHTML = message;
});
}
</script>
</head>
<body>
<button onclick="HandleButton(event);">Get the Secret Message!</button>
<div id="message"></div>
</body>
</html>
)";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment