Skip to content

Commit

Permalink
Use callbacks for webview bindings to enable async behavior (#2)
Browse files Browse the repository at this point in the history
  • Loading branch information
nick-thompson committed Mar 22, 2024
1 parent 3c23805 commit f5491e1
Showing 1 changed file with 16 additions and 9 deletions.
25 changes: 16 additions & 9 deletions gui/choc_WebView.h
Expand Up @@ -135,7 +135,8 @@ class WebView
void navigate (const std::string& url);

/// A callback function which can be passed to bind().
using CallbackFn = std::function<choc::value::Value(const choc::value::ValueView& args)>;
using ReplyFn = std::function<void(choc::value::Value, std::string)>;
using CallbackFn = std::function<void(const choc::value::ValueView& args, ReplyFn&& reply)>;
/// Binds a C++ function to a named javascript function that can be called
/// by code running in the browser.
void bind (const std::string& functionName, CallbackFn&& function);
Expand Down Expand Up @@ -1495,17 +1496,23 @@ inline void WebView::invokeBinding (const std::string& msg)

try
{
auto result = b->second (json["params"]);
b->second (json["params"], [=](choc::value::Value result, std::string const& errorMessage) {
if (!errorMessage.empty())
{
auto call = callbackItem + ".reject(" + choc::json::toString(choc::value::createString(errorMessage)) + "); delete " + callbackItem + ";";
evaluateJavascript (call);
return;
}

auto call = callbackItem + ".resolve(" + choc::json::toString (result) + "); delete " + callbackItem + ";";
auto call = callbackItem + ".resolve(" + choc::json::toString (result) + "); delete " + callbackItem + ";";
evaluateJavascript (call);
});
}
catch (const std::exception& e)
{
auto call = callbackItem + ".reject(" + choc::json::toString(choc::value::createString(e.what())) + "); delete " + callbackItem + ";";
evaluateJavascript (call);
return;
}
catch (const std::exception&)
{}

auto call = callbackItem + ".reject(); delete " + callbackItem + ";";
evaluateJavascript (call);
}
catch (const std::exception&)
{}
Expand Down

0 comments on commit f5491e1

Please sign in to comment.