예제 #1
0
파일: JsBinding.cs 프로젝트: enklu/orchid
        /// <summary>
        /// This method binds a function to a specific field on a JavaScript object.
        /// </summary>
        /// <param name="name">The name of the field.</param>
        /// <param name="jsFunction">The callback function to execute when the JavaScript function is invoked.</param>
        public void AddFunction(string name, JavaScriptNativeFunction jsFunction)
        {
            _scope.Run(() =>
            {
                var jsValue = _binder.BindFunction(jsFunction);

                _value.SetProperty(JavaScriptPropertyId.FromString(name), jsValue, true);
            });
        }
예제 #2
0
        /// <summary>
        /// Creates a <see cref="JavaScriptValue"/> representing the host delegate.
        /// </summary>
        /// <remarks>This call requires an active context.</remarks>
        public JavaScriptValue ToJsFunction(object obj, Type type)
        {
            var invokeInfo = type.GetMethod("Invoke");

            if (null == invokeInfo)
            {
                throw new Exception($"Cannot convert delegate of type: {type} to JavaScript function.");
            }

            JavaScriptNativeFunction func = (v, s, args, argLength, data) =>
            {
                var parameters = invokeInfo.GetParameters();
                var realParams = new object[parameters.Length];
                var argIndex   = 1;
                for (int j = 0; j < parameters.Length; ++j)
                {
                    var arg   = args[argIndex++];
                    var param = parameters[j];

                    realParams[j] = ToHostObject(arg, param.ParameterType);
                }

                var result     = invokeInfo.Invoke(obj, realParams);
                var resultType = invokeInfo.ReturnType;
                if (resultType == typeof(void))
                {
                    return(JavaScriptValue.Invalid);
                }

                return(ToJsObject(result, JsConversions.TypeFor(result, resultType)));
            };

            return(_binder.BindFunction(func));
        }