Ejemplo n.º 1
0
        // Example: Map the CLR objects to NanUI's JavaScript context.
        private void MapClrObjectToJavaScript()
        {
            var obj = JavaScriptValue.CreateObject();

            // Readonly property
            obj.SetValue("now", JavaScriptValue.CreateProperty(() =>
            {
                return(JavaScriptValue.CreateDateTime(DateTime.Now));
            }));

            // Value
            obj.SetValue("version", JavaScriptValue.CreateString(Assembly.GetExecutingAssembly().GetName().Version?.ToString()));

            // Readable and writable property
            obj.SetValue("subtitle", JavaScriptValue.CreateProperty(() => JavaScriptValue.CreateString(Subtitle), title => Subtitle = title.GetString()));

            // Sync method
            obj.SetValue("messagebox", JavaScriptValue.CreateFunction(args =>
            {
                var msg = args.FirstOrDefault(x => x.IsString);

                var text = msg?.GetString();

                InvokeIfRequired(() =>
                {
                    MessageBox.Show(HostWindow, text, "Message from JS", MessageBoxButtons.OK, MessageBoxIcon.Information);
                });

                return(JavaScriptValue.CreateString(text));
            }));

            // Async method
            obj.SetValue("asyncmethod", JavaScriptValue.CreateFunction((args, callback) =>
            {
                Task.Run(async() =>
                {
                    var rnd = new Random(DateTime.Now.Millisecond);

                    var rndValue = rnd.Next(1000, 2000);

                    await Task.Delay(rndValue);
                    var obj = JavaScriptValue.CreateObject();

                    obj.SetValue("delayed", JavaScriptValue.CreateNumber(rndValue));
                    obj.SetValue("message", JavaScriptValue.CreateString($"Delayed {rndValue} milliseconds"));


                    callback.Success(obj);
                });
            }));

            RegisterExternalObjectValue("tester", obj);
        }