/// <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); }); }
/// <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)); }