如何将 javascript 框架注入 ChakraBridge 上下文?

How into inject javascript frameworks into ChakraBridge context?

我正在尝试使用 ChakraBridge 库在我的 UWP 应用程序中使用 math.js。我参考了以下 link 在 UWP 应用程序中使用 javascript 框架。 http://www.codeproject.com/Articles/1060634/Using-JavaScript-frameworks-from-your-Csharp-UWP-a

但我不知道如何将 javascirpt 框架注入 Chakra 上下文。 link 说使用方法 "ReadAndExecute" 或 "DownloadAndExecute",但我在 ChakraBridge 库的任何 类 中都找不到这些方法。 那么如何将 *.js 文件注入 ChakraBridge 上下文?

The link says use the method "ReadAndExecute" or "DownloadAndExecute", but I could not find those methods in any of the classes of ChakraBridge library.

这两个方法应该由编码器定义。它们记录在 ChakraBridge GitHub Site 中。它们如下所示:

async Task ReadAndExecute(string filename)
{
    //"js" is the folder name of your javascript library.
    var script = await CoreTools.GetPackagedFileContentAsync("js", filename);
    host.RunScript(script);
}

async Task DownloadAndExecute(string url)
{
    var script = await CoreTools.DownloadStringAsync(url);
    host.RunScript(script);
}

因此,将 *.js 文件注册到 ChakraBridge 上下文中。只需像下面这样调用这两个方法:

string url = @"http://cdnjs.cloudflare.com/ajax/libs/mathjs/3.2.1/math.js";
await DownloadAndExecute(url);//load math.js from remote source.
await ReadAndExecute("math.js");//load math.js from local source.
await ReadAndExecute("main.js");//main.js is the custom js codes. You can utilize math.js here.

这是我制作的基本演示的 link:ChakraBridgeSample

备注:

  1. Newtonsoft.Json 应该在您的项目中作为准备工作被引用。它可以通过在 Nuget 包管理器上搜索或通过 Nuget 包管理器控制台安装:"Install-Package Newtonsoft.Json".
  2. 注册 CommunicationManager.OnObjectReceived 事件的行为与 GitHub 文档略有不同。不再有类型参数(只有数据参数)。所以在 javascript 端,sendToHost 函数应该如下所示:

    var data = math.atan2(3, -3) / math.pi;
    // "Double" should match the typeof(Double) in C# side. Capitalizing is necessary.
    sendToHost(JSON.stringify(data), "Double");