public ClrProperty(global::Jint.Engine engine, DomConverter converter, PropertyInfo property) { Get = property.GetMethod != null && property.GetMethod.IsPublic ? new ClrFunctionInstance(engine, (jsThis, values) => { var clrThis = converter.ConvertFromJs(jsThis); return(JsValue.FromObject(engine, property.GetValue(clrThis))); }) : null; var setter = new Lazy <Action <object, JsValue> >(() => CreateSetter(converter, property)); Set = property.SetMethod != null && property.SetMethod.IsPublic ? new ClrFunctionInstance(engine, (jsThis, values) => { try { var clrThis = converter.ConvertFromJs(jsThis); if (values.Length == 0) { return(JsValue.Undefined); } setter.Value(clrThis, values[0]); return(JsValue.Undefined); } catch (Exception e) { throw new JavaScriptException(e.Message); } }) : new ClrFunctionInstance(engine, (value, values) => JsValue.Undefined); }
public ClrEvent(global::Jint.Engine engine, DomConverter converter, EventInfo eventInfo) { Get = new ClrFunctionInstance(engine, (clrThis, args) => { var attachedEvents = converter.GetAttachedEventsFor(clrThis); return(attachedEvents.TryGetValue(eventInfo, out var func) ? func : JsValue.Null); }); Set = new ClrFunctionInstance(engine, (jsThis, args) => { var objectInstance = jsThis.AsObject(); var clrThis = converter.ConvertFromJs(jsThis); var attachedEvents = converter.GetAttachedEventsFor(objectInstance); if (attachedEvents.TryGetValue(eventInfo, out var existHandler)) { var clrHandler = converter.ConvertToClr(existHandler, eventInfo.EventHandlerType, jsThis); eventInfo.RemoveMethod.Invoke(clrThis, new object[] { clrHandler }); attachedEvents.Remove(eventInfo); } if (args.Length != 0 && !args[0].IsNull() && !args[0].IsUndefined() && args[0].AsObject() is FunctionInstance functionInstance) { var clrHandler = converter.ConvertToClr(functionInstance, eventInfo.EventHandlerType, jsThis); eventInfo.AddMethod.Invoke(clrThis, new object[] { clrHandler }); attachedEvents[eventInfo] = functionInstance; } return(null); }); }
public override JsValue Call(JsValue thisObject, JsValue[] argumentValues) { int methodIndex = _methods.IndexOf(x => x.GetParameters().IsAppropriate(argumentValues, true)); if (methodIndex < 0) { methodIndex = _methods.IndexOf(x => x.GetParameters().IsAppropriate(argumentValues, false)); } if (methodIndex < 0) { return(null); //or throw exception; } var invoker = _invokers[methodIndex]; if (invoker == null) { _invokers[methodIndex] = invoker = CreateInvoker(_methods[methodIndex]); } var clrObject = _converter.ConvertFromJs(thisObject == JsValue.Undefined ? _owner : thisObject); if (clrObject is ClrPrototype prototype) { if (_methods.Length == 1 && _methods[0].Name == "ToString") { return($"[object {prototype.Class}]"); } throw new JavaScriptException("Illegal method invocation."); } try { return(JsValue.FromObject(Engine, invoker(clrObject, argumentValues))); } catch (Exception e) { throw new JavaScriptException(e.ToString()); } }