예제 #1
0
        /// <summary>
        /// Creates the <see cref="JsBinding"/> instance representing the new bound JavaScript object.
        /// </summary>
        public JsBinding Build()
        {
            return(_scope.Run(() =>
            {
                // Create a host object binding or new JS Object binding
                var jsValue = null != _boundTo
                    ? _binder.BindObject(_boundTo)
                    : JavaScriptValue.CreateObject();

                var binding = new JsBinding(_scope, _binder, _interop, jsValue);

                // Bind Host Object Methods, Properties, and Fields if bound to host object
                if (null != _boundTo && null != _hostType)
                {
                    BindMethods(binding, _hostType, _boundTo);
                    BindProperties(binding, _hostType, _boundTo);
                    BindFields(binding, _hostType, _boundTo);
                }

                // Set custom binding values
                if (null != _values)
                {
                    for (int i = 0; i < _values.Count; ++i)
                    {
                        var valueDescriptor = _values[i];
                        binding.SetValue(valueDescriptor.Name, valueDescriptor.Value, valueDescriptor.ValueType);
                    }
                }

                return binding;
            }));
        }
예제 #2
0
        public void Init()
        {
            JavaScriptNativeFunction printFunc = PrintFunc;

            registeredFunctions.Add(printFunc);
            JavaScriptNativeFunction httpFunc = JsXmlHttpRequest.JsConstructor;

            registeredFunctions.Add(httpFunc);

            using (new JavaScriptContext.Scope(context)) {
                var printFuncName = JavaScriptPropertyId.FromString("print");
                var printFuncObj  = JavaScriptValue.CreateFunction(printFunc);
                JavaScriptValue.GlobalObject.SetProperty(printFuncName, printFuncObj, true);

                var logObj      = JavaScriptValue.CreateObject();
                var logFuncName = JavaScriptPropertyId.FromString("log");
                logObj.SetProperty(logFuncName, printFuncObj, true);

                var consoleName = JavaScriptPropertyId.FromString("console");
                JavaScriptValue.GlobalObject.SetProperty(consoleName, logObj, true);

                var xmlHttpRequestName = JavaScriptPropertyId.FromString("XMLHttpRequest");
                var httpFuncObj        = JavaScriptValue.CreateFunction(httpFunc);
                JavaScriptValue.GlobalObject.SetProperty(xmlHttpRequestName, httpFuncObj, true);
            }
        }
예제 #3
0
        public void RegisterObject(string name, object obj)
        {
            var type = obj.GetType();

            using (new JavaScriptContext.Scope(context)) {
                var jsObj = JavaScriptValue.CreateObject();

                foreach (var m in type.GetMethods())
                {
                    var attrib = m.GetCustomAttribute <JsExport>();
                    if (attrib == null)
                    {
                        continue;
                    }

                    var funcName     = attrib.JavaScriptMethodName ?? m.Name;
                    var funcNameProp = JavaScriptPropertyId.FromString(funcName);

                    var funcDelegate = (JavaScriptNativeFunction)Delegate.CreateDelegate(typeof(JavaScriptNativeFunction), obj, m);
                    registeredFunctions.Add(funcDelegate);
                    var funcObj = JavaScriptValue.CreateFunction(funcDelegate);

                    jsObj.SetProperty(funcNameProp, funcObj, true);
                }

                var nameProp = JavaScriptPropertyId.FromString(name);
                JavaScriptValue.GlobalObject.SetProperty(nameProp, jsObj, true);
            }
        }
        private void InitializeChakra()
        {
            JavaScriptContext.Current = _runtime.CreateContext();

            var consolePropertyId = default(JavaScriptPropertyId);

            Native.ThrowIfError(
                Native.JsGetPropertyIdFromName("console", out consolePropertyId));

            var consoleObject = JavaScriptValue.CreateObject();

            EnsureGlobalObject().SetProperty(consolePropertyId, consoleObject, true);

            _consoleInfo  = ConsoleInfo;
            _consoleLog   = ConsoleLog;
            _consoleWarn  = ConsoleWarn;
            _consoleError = ConsoleError;

            DefineHostCallback(consoleObject, "info", _consoleInfo);
            DefineHostCallback(consoleObject, "log", _consoleLog);
            DefineHostCallback(consoleObject, "warn", _consoleWarn);
            DefineHostCallback(consoleObject, "error", _consoleError);

            Debug.WriteLine("Chakra initialization successful.");
        }
예제 #5
0
파일: MainForm.cs 프로젝트: LSluoshi/NanUI
        // Example: Register JavaScript object in current frame.
        private void RegisterJavaScriptExampleObject()
        {
            var jsDemo = JavaScriptValue.CreateObject();

            jsDemo.SetValue("executeJavaScriptWithoutRetval", JavaScriptValue.CreateFunction(args =>
            {
                InvokeIfRequired(() =>
                {
                    ExecuteJavaScript("alert(1+1)");
                });
                return(null);
            }));

            jsDemo.SetValue("executeJavaScriptWithRetval", JavaScriptValue.CreateFunction(args =>
            {
                InvokeIfRequired(async() =>
                {
                    var result = await EvaluateJavaScriptAsync("(function(){ return {a:1,b:'hello',c:(s)=>alert(s)}; })()");
                    if (result.Success)
                    {
                        var retval = result.ResultValue;
                        MessageBox.Show($"a={retval.GetInt("a")} b={retval.GetString("b")}", "Value from JS");
                        await retval.GetValue("c").ExecuteFunctionAsync(GetMainFrame(), new JavaScriptValue[] { JavaScriptValue.CreateString("Hello from C#") });
                    }
                });
                return(null);
            }));

            RegisterExternalObjectValue("jsExamples", jsDemo);
        }
예제 #6
0
        public static void Register(JavaScriptContext context)
        {
            JavaScriptValue symbolGlobal = JavaScriptValue.GlobalObject.GetProperty("Symbol");

            modulesSymbol = symbolGlobal.GetProperty("for").CallFunction(symbolGlobal, JavaScriptValue.FromString("typescript-for-unity.importedRootModules"));
            modulesSymbol.AddRef();
            JavaScriptValue.GlobalObject.SetProperty(modulesSymbol, JavaScriptValue.CreateObject());
        }
예제 #7
0
        private JSValue createStubValue()
        {
            JSValue stub = new JSValue(apiContainer.ServiceNode, JavaScriptValue.CreateObject());
            string  id   = "__NativeAPI__" + Guid.NewGuid().ToString().Replace('-', '_');

            apiContainer.WriteProperty(id, stub);
            return(stub);
        }
예제 #8
0
        public static void Register(JavaScriptContext context)
        {
            var UnityEngineNetworkingGlobal = JavaScriptValue.CreateObject();

            JavaScriptValue.GlobalObject.GetProperty("UnityEngine").GetProperty("Networking").SetProperty("PlayerConnection", UnityEngineNetworkingGlobal);

            JSMessageEventArgs.Register(context);
            JSPlayerConnection.Register(context);
        }
예제 #9
0
        public static void Register(JavaScriptContext context)
        {
            var SystemCollectionsGlobal = JavaScriptValue.CreateObject();

            JavaScriptValue.GlobalObject.GetProperty("System").SetProperty("Collections", SystemCollectionsGlobal);

            JSIEnumerator.Register(context);
            JSIEnumerable.Register(context); // this might conflict with the magic prototype parent finder
        }
예제 #10
0
        public static void Register(JavaScriptContext context)
        {
            updateCallbacks.Clear();
            oneUpdateCallbacks.Clear();

            JavaScriptValue UpdateHelper = JavaScriptValue.CreateObject();

            JavaScriptValue.GlobalObject.SetProperty(
                "UpdateHelper",
                UpdateHelper
                );

            UpdateHelper.SetProperty(
                "addUpdateHook",
                Bridge.CreateFunction(
                    "addUpdateHook",
                    (args) => {
                return(JavaScriptValue.FromString(
                           addUpdateHook(args[1])
                           ));
            }
                    )
                );

            UpdateHelper.SetProperty(
                "removeUpdateHook",
                Bridge.CreateFunction(
                    "removeUpdateHook",
                    (args) => {
                removeUpdateHook(args[1].ToString());
            }
                    )
                );

            UpdateHelper.SetProperty(
                "removeAllUpdateHooks",
                Bridge.CreateFunction(
                    "removeAllUpdateHooks",
                    (args) => {
                updateCallbacks.Clear();
                oneUpdateCallbacks.Clear();
            }
                    )
                );

            UpdateHelper.SetProperty(
                "addOneUpdateHook",
                Bridge.CreateFunction(
                    "addOneUpdateHook",
                    (args) => {
                addOneUpdateHook(args[1]);
            }
                    )
                );
        }
예제 #11
0
            private void DefineEcho()
            {
                var globalObject = JavaScriptValue.GlobalObject;

                var hostObject     = JavaScriptValue.CreateObject();
                var hostPropertyId = JavaScriptPropertyId.FromString("managedhost");

                globalObject.SetProperty(hostPropertyId, hostObject, true);
                EchoDelegate = Echo;
                DefineCallback(hostObject, "echo", EchoDelegate);
            }
예제 #12
0
 public void Why()
 {
     using (var c = MakeController())
     {
         var o  = new Object();
         var v1 = JavaScriptValue.CreateExternalObject(GCHandle.ToIntPtr(GCHandle.Alloc(o)), Free);
         Assert.IsTrue(v1.HasExternalData == true);
         var v2 = JavaScriptValue.CreateObject();
         Assert.IsTrue(v2.HasExternalData == false); // !?
     }
 }
예제 #13
0
        public static void Register(JavaScriptContext context)
        {
            var SystemGlobal = JavaScriptValue.CreateObject();

            JavaScriptValue.GlobalObject.SetProperty("System", SystemGlobal);

            // things that don't extend
            JSObject.Register(context);

            Collections.JSSystemCollections.Register(context);
        }
예제 #14
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);
        }
예제 #15
0
        private JavaScriptValue GetCultureInfo(Formium owner, JavaScriptValue[] arguments)
        {
            var retval = JavaScriptValue.CreateObject();

            retval.SetValue("name", JavaScriptValue.CreateString($"{Thread.CurrentThread.CurrentCulture.Name}"));

            retval.SetValue("displayName", JavaScriptValue.CreateString($"{Thread.CurrentThread.CurrentCulture.DisplayName}"));
            retval.SetValue("englishName", JavaScriptValue.CreateString($"{Thread.CurrentThread.CurrentCulture.EnglishName}"));

            retval.SetValue("lcid", JavaScriptValue.CreateNumber(Thread.CurrentThread.CurrentCulture.LCID));

            return(retval);
        }
예제 #16
0
        public static void Register(JavaScriptContext context)
        {
            JavaScriptValue
            .GlobalObject
            .GetProperty("UnityEngine")
            .SetProperty("EventSystems", JavaScriptValue.CreateObject());

            JSAbstractEventData.Register(context);
            JSMoveDirection.Register(context);
            JSBaseEventData.Register(context);
            JSAxisEventData.Register(context);
            JSPointerEventData.Register(context);
        }
예제 #17
0
        public static void Register(JavaScriptContext context)
        {
            JavaScriptValue ChakraGlobal = JavaScriptValue.CreateObject();

            JavaScriptValue.GlobalObject.SetProperty("chakra", ChakraGlobal);

            ChakraGlobal.SetProperty(
                "CollectGarbage",
                Bridge.CreateFunction("CollectGarbage", (args) => {
                context.GetRuntime().CollectGarbage();
            })
                );
        }
예제 #18
0
        static JavaScriptContext _create_context(JavaScriptRuntime runtime)
        {
            JavaScriptContext context = runtime.CreateContext();

            using (new JavaScriptContext.Scope(context))
            {
                JavaScriptValue      hostObject_API     = JavaScriptValue.CreateObject();
                JavaScriptPropertyId hostPropertyId_API = JavaScriptPropertyId.FromString("___api");
                JavaScriptValue.GlobalObject.SetProperty(hostPropertyId_API, hostObject_API, true);
                _register(hostObject_API);
            }
            return(context);
        }
예제 #19
0
        private JavaScriptValue VisitObject(JObject token)
        {
            var jsonObject = JavaScriptValue.CreateObject();

            foreach (var entry in token)
            {
                var value      = Visit(entry.Value);
                var propertyId = JavaScriptPropertyId.FromString(entry.Key);
                jsonObject.SetProperty(propertyId, value, true);
            }

            return(jsonObject);
        }
예제 #20
0
파일: JsBinding.cs 프로젝트: enklu/orchid
        /// <summary>
        /// This method binds a getter and setter function to a specific field on a JavaScript object.
        /// </summary>
        /// <param name="name">The name of the field.</param>
        /// <param name="getter">The function to invoke when the field is read.</param>
        /// <param name="setter">The function to invoke when the field is written to.</param>
        public void AddProperty(string name, JavaScriptNativeFunction getter, JavaScriptNativeFunction setter)
        {
            _scope.Run(() =>
            {
                var get = _binder.BindFunction(getter);
                var set = _binder.BindFunction(setter);

                var descriptor = JavaScriptValue.CreateObject();
                descriptor.SetProperty(JavaScriptPropertyId.FromString("get"), get, true);
                descriptor.SetProperty(JavaScriptPropertyId.FromString("set"), set, true);

                _value.DefineProperty(JavaScriptPropertyId.FromString(name), descriptor);
            });
        }
예제 #21
0
        public async void ProcessFrame(FrameData frame)
        {
            if (callbacks.Count == 0 || busy)
            {
                return;
            }
            else
            {
                busy = true;
            }

            var bitmap = frame.bitmap;

            if (!FaceDetector.IsBitmapPixelFormatSupported(bitmap.BitmapPixelFormat))
            {
                bitmap = SoftwareBitmap.Convert(bitmap, BitmapPixelFormat.Gray8);
            }

            var detectedFaces = await faceDetector.DetectFacesAsync(bitmap);

            int frameKey = -1;

            if (detectedFaces.Count > 0)
            {
                frameKey = SceneCameraManager.Inst.AddFrameToCache(frame);
            }

            ProjectRuntime.Inst.DispatchRuntimeCode(() => {
                var jsImg = JavaScriptValue.CreateObject();
                jsImg.SetProperty(JavaScriptPropertyId.FromString("id"), JavaScriptValue.FromInt32(frameKey), true);
                Native.JsSetObjectBeforeCollectCallback(jsImg, IntPtr.Zero, jsObjectCallback);

                var faces    = JavaScriptValue.CreateArray(0);
                var pushFunc = faces.GetProperty(JavaScriptPropertyId.FromString("push"));
                foreach (var face in detectedFaces)
                {
                    var pos    = GetEstimatedPositionFromFaceBounds(face.FaceBox, frame.bitmap);
                    var jsFace = JavaScriptContext.RunScript($"new Face(new Position({pos.X}, {pos.Y}, {pos.Z}), {0});");
                    jsFace.SetProperty(JavaScriptPropertyId.FromString("frame"), jsImg, true);
                    jsFace.SetProperty(JavaScriptPropertyId.FromString("bounds"), face.FaceBox.ToJavaScriptValue(), true);
                    pushFunc.CallFunction(faces, jsFace);
                }
                foreach (var callback in callbacks)
                {
                    callback.CallFunction(callback, faces);
                }
            });

            busy = false;
        }
예제 #22
0
        public static void Register(JavaScriptContext context)
        {
            JavaScriptValue console = JavaScriptValue.CreateObject();

            JavaScriptValue.GlobalObject.SetProperty(
                "console",
                console
                );

            foreach (var pair in new Dictionary <string, Action <JavaScriptValue[]> >()
            {
                {
                    "_log",
                    (arguments) => {
                        Debug.Log(getFormattedString(arguments, ConvertToString()));
                    }
                }, {
                    "_warn",
                    (arguments) => {
                        Debug.LogWarning(getFormattedString(arguments, ConvertToString()));
                    }
                }, {
                    "_error",
                    (arguments) => {
                        Debug.LogError(getFormattedString(arguments, ConvertToString()));
                    }
                }, {
                    "log",
                    (arguments) => {
                        Debug.Log(getFormattedString(arguments, Inspect()));
                    }
                }, {
                    "warn",
                    (arguments) => {
                        Debug.LogWarning(getFormattedString(arguments, Inspect()));
                    }
                }, {
                    "error",
                    (arguments) => {
                        Debug.LogError(getFormattedString(arguments, Inspect()));
                    }
                }
            })
            {
                console.SetProperty(
                    pair.Key,
                    Bridge.CreateFunction(pair.Key, pair.Value)
                    );
            }
        }
예제 #23
0
        private JavaScriptValue GetWindowRectangle(Formium owner, JavaScriptValue[] arguments)
        {
            var retval = JavaScriptValue.CreateObject();

            var rect = new RECT();

            User32.GetWindowRect(owner.HostWindowHandle, ref rect);

            retval.SetValue("x", JavaScriptValue.CreateNumber(rect.left));
            retval.SetValue("y", JavaScriptValue.CreateNumber(rect.top));
            retval.SetValue("width", JavaScriptValue.CreateNumber(rect.Width));
            retval.SetValue("height", JavaScriptValue.CreateNumber(rect.Height));

            return(retval);
        }
예제 #24
0
        private static void WireUp(JavaScriptValue constructor, System.Type type, JavaScriptValue prototype)
        {
            string name = type.ToString();

            typeNameToType[name] = type;

            // So that we can look up c# types by JS constructors, define a name property containing
            // the full name from type.ToString() that we can take off and put back into stringToType.
            JavaScriptValue propertyDescriptor = JavaScriptValue.CreateObject();

            propertyDescriptor.SetProperty("value", JavaScriptValue.FromString(name));
            constructor.DefineProperty("name", propertyDescriptor);

            typeNameToPrototype[name] = prototype;
        }
예제 #25
0
파일: MainForm.cs 프로젝트: LSluoshi/NanUI
        // Add methods for demo object in Formium.external object in JavaScript context.
        private void RegisterDemoWindowlObject()
        {
            var demoWindow = JavaScriptValue.CreateObject();

            const string GITHUB_URL = "https://github.com/NetDimension/NanUI";

            demoWindow.SetValue("openLicenseWindow", JavaScriptValue.CreateFunction(args =>
            {
                InvokeIfRequired(() =>
                {
                    ShowAboutDialog();
                });

                return(null);
            }));

            demoWindow.SetValue("navigateToGitHub", JavaScriptValue.CreateFunction(args =>
            {
                InvokeIfRequired(() =>
                {
                    OpenExternalUrl(GITHUB_URL);
                });

                return(null);
            }));

            demoWindow.SetValue("openDevTools", JavaScriptValue.CreateFunction(args =>
            {
                InvokeIfRequired(() =>
                {
                    ShowDevTools();
                });

                return(null);
            }));

            demoWindow.SetValue("openLocalFileResourceFolder", JavaScriptValue.CreateFunction(args =>
            {
                InvokeIfRequired(() =>
                {
                    OpenExternalUrl(System.IO.Path.Combine(Application.StartupPath, "LocalFiles"));
                });

                return(null);
            }));

            RegisterExternalObjectValue("demo", demoWindow);
        }
예제 #26
0
        private Tuple <ChakraContext, JSValue> CreateChakraContext()
        {
            JavaScriptHosting       hosting = JavaScriptHosting.Default; //get default host instantce
            JavaScriptHostingConfig config  = new JavaScriptHostingConfig();

            config.AddModuleFolder("wwwroot/dist/js"); //set script folder

            var chakraContext = hosting.CreateContext(config);

            // Function Converter
            var valueServices = chakraContext.ServiceNode.GetService <IJSValueConverterService>();

            valueServices.RegisterFunctionConverter <string>();
            valueServices.RegisterProxyConverter <EvConsole>((binding, instance, serviceNode) =>
            {
                binding.SetMethod <string>("log", instance.Log);
            });

            // EvContext Converter
            valueServices.RegisterStructConverter <EvContext>((to, from) => { to.WriteProperty("title", from.Title); },
                                                              (from) => new EvContext
            {
                Title = from.ReadProperty <string>("title")
            });

            var console = new EvConsole();

            chakraContext.GlobalObject.WriteProperty("console", console);

            chakraContext.Enter();
            // https://ssr.vuejs.org/guide/non-node.html
            var obj = JavaScriptValue.CreateObject();

            obj.SetProperty(JavaScriptPropertyId.FromString("VUE_ENV"), JavaScriptValue.FromString("server"), false);
            obj.SetProperty(JavaScriptPropertyId.FromString("NODE_ENV"), JavaScriptValue.FromString("production"),
                            false);

            var process = JavaScriptValue.CreateObject();

            process.SetProperty(JavaScriptPropertyId.FromString("env"), obj, false);

            chakraContext.GlobalObject.WriteProperty(JavaScriptPropertyId.FromString("process"), process);
            chakraContext.Leave();

            var appClass = chakraContext.ProjectModuleClass("entrypoint", "App", config.LoadModule);

            return(Tuple.Create(chakraContext, appClass));
        }
        private JavaScriptContext CreateHostWebsocketContext(JavaScriptRuntime runtime, string clientId, string text, Stream binaryStream, bool isStream)
        {
            // Create the context. Note that if we had wanted to start debugging from the very
            // beginning, we would have called JsStartDebugging right after context is created.
            JavaScriptContext context = runtime.CreateContext();

            // Now set the execution context as being the current one on this thread.
            using (new JavaScriptContext.Scope(context))
            {
                // Create the host object the script will use.
                JavaScriptValue hostObject = JavaScriptValue.CreateObject();

                // Get the global object
                JavaScriptValue globalObject = JavaScriptValue.GlobalObject;

                // Get the name of the property ("host") that we're going to set on the global object.
                JavaScriptPropertyId hostPropertyId = JavaScriptPropertyId.FromString("host");

                // Set the property.
                globalObject.SetProperty(hostPropertyId, hostObject, true);

                // Now create the host callbacks that we're going to expose to the script.
                DefineHostCallback(hostObject, "echo", echoDelegate, IntPtr.Zero);
                DefineHostCallback(hostObject, "runScript", runScriptDelegate, IntPtr.Zero);
                DefineHostCallback(hostObject, "readFile", readFileDelegate, IntPtr.Zero);
                DefineHostCallback(hostObject, "writeFile", writeFileDelegate, IntPtr.Zero);
                DefineHostCallback(hostObject, "websocketClients", getWebSocketClientIdDelegate, IntPtr.Zero);
                DefineHostCallback(hostObject, "websocketPush", pushWebSocketMessageDelegate, IntPtr.Zero);

                JavaScriptValue requestParams = JavaScriptValue.CreateObject();
                if (isStream)
                {
                    requestParams.SetProperty(JavaScriptPropertyId.FromString("blob"), JavaScriptValue.FromString(text), true);
                    // not implemented yet #todo
                }
                else
                {
                    requestParams.SetProperty(JavaScriptPropertyId.FromString("text"), JavaScriptValue.FromString(text), true);
                }
                requestParams.SetProperty(JavaScriptPropertyId.FromString("clientId"), JavaScriptValue.FromString(clientId), true);

                hostObject.SetProperty(JavaScriptPropertyId.FromString("request"), requestParams, true);
            }

            return(context);
        }
예제 #28
0
        /// <summary>
        /// Creates a new <see cref="JsModule"/> instance.
        /// </summary>
        public JsModule(JsContextScope scope, JsBinder binder, JsInterop interop, string moduleId)
        {
            _scope   = scope;
            _binder  = binder;
            _interop = interop;

            ModuleId = moduleId;

            // Create JS Representation
            Module = _scope.Run(() =>
            {
                var jsValue = JavaScriptValue.CreateObject();
                jsValue.AddRef();

                return(new JsBinding(_scope, _binder, _interop, jsValue));
            });
        }
예제 #29
0
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                runtime = JavaScriptRuntime.Create();
                context = runtime.CreateContext();
                JavaScriptContext.Current = context;

                JavaScriptValue      hostObject     = JavaScriptValue.CreateObject();
                JavaScriptValue      globalObject   = JavaScriptValue.GlobalObject;
                JavaScriptPropertyId hostPropertyId = JavaScriptPropertyId.FromString("host");
                globalObject.SetProperty(hostPropertyId, hostObject, true);

                JavaScriptValue      delegateObject     = JavaScriptValue.CreateObject();
                JavaScriptPropertyId delegatePropertyId = JavaScriptPropertyId.FromString("delegate");
                globalObject.SetProperty(delegatePropertyId, delegateObject, true);

                DefineHostCallback(delegateObject, "ballCountChanged", onBallCountChanged, IntPtr.Zero);
                DefineHostCallback(delegateObject, "displayListChanged", onDisplayListChanged, IntPtr.Zero);
                DefineHostCallback(delegateObject, "eventsPerSecond", onEventsPerSecond, IntPtr.Zero);
                DefineHostCallback(delegateObject, "phaseChanged", onPhaseChanged, IntPtr.Zero);
                DefineHostCallback(delegateObject, "measureText", onMeasureText, IntPtr.Zero);
                DefineHostCallback(delegateObject, "log", onLog, IntPtr.Zero);

                Uri uri = new Uri("/model.js", UriKind.Relative);
                StreamResourceInfo     info = Application.GetContentStream(uri);
                System.IO.StreamReader sr   = new System.IO.StreamReader(info.Stream);
                string          script      = sr.ReadToEnd();
                JavaScriptValue result      = JavaScriptContext.RunScript(script);

                script = "var controller = initApp(" + balls.ActualWidth + ", " + balls.ActualHeight + ", delegate);";
                result = JavaScriptContext.RunScript(script);
            }
            catch (JavaScriptScriptException ex)
            {
                PrintScriptException(ex.Error);
            }
            catch (Exception ex)
            {
                Debug.WriteLine("chakrahost: failed to run script: {0}", ex.Message);
            }

            timer          = new Timer(1.0 / 30.0 * 1000.0);
            timer.Elapsed += new ElapsedEventHandler(TimerFired);
            timer.Enabled  = true;
        }
예제 #30
0
        public static void DefineGetter(
            JavaScriptValue obj,
            string keyName,
            Func <JavaScriptValue[], JavaScriptValue> callback
            )
        {
            JavaScriptValue descriptor = JavaScriptValue.CreateObject();

            descriptor.SetProperty(
                "get",
                FunctionAllocation.CreateFunction(callback)
                );
            obj.DefineProperty(
                keyName,
                descriptor
                );
        }