-
|
I've some special types which require conversion from dotnet to js, and back from js to dotnet when calling I pasted some sample code below, where I'm registering custom converters to convert my special "Percent" type (AddObjectConverter and SetTypeConverter). Is it correct to inherit and override the default behaviour of "DefaultTypeConverter" to ensure, that my custom type is converted back to the dotnet type correctly? public class Percent {
public decimal Value { get; set; }
}
public class Employee {
public Percent LevelOfEmployment { get; set; }
}
var employees = new Employee[] { new Employee { ... } };
var engine = new Engine(options => {
// Registering custom converter to convert from dotnet to js
options.AddObjectConverter(new DotNetToJsConverter());
// Registering custom converter to convert from js back to dotnet
options.SetTypeConverter(engine => new JsToDotNetConverter(engine));
});
engine.Execute(@"function myFunction(employees) {
// doing things with employees in js
// ...
return employees;
}");
var updatedEmployees = engine.Invoke("myFunction", JsValue.FromObject(engine, employees)).ToObject()
Assert.That(updatedEmployees.First().LevelOfEmployment.GetType() == typeof(Percent), "should be correct dotnet type");public class DotNetToJsConverter : Jint.Runtime.Interop.IObjectConverter {
public bool TryConvert(Engine engine, object value, out JsValue result) {
if (value is Prozent prozent) {
result = JsValue.FromObject(engine, prozent.Value);
return true;
}
return false;
}
}
public class JsToDotNetConverter : Jint.Runtime.Interop.DefaultTypeConverter
{
public JsToDotNetConverter(Jint.Engine engine) : base(engine) {}
public override object Convert(object value, Type type, IFormatProvider formatProvider) {
return type == typeof(Prozent)
? new Prozent { Value = value }
: base.Convert(value, type, formatProvider);
}
public override bool TryConvert(object value, Type type, IFormatProvider formatProvider, out object converted) {
if (type == typeof(Prozent))
{
converted = new Prozent { Value = value };
return true;
}
return base.TryConvert(value, type, formatProvider, out converted);
}
} |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
|
I think your current setup looks valid. One thing on Jint's side is to consider if we need to make things a bit more obvious. Like allowing conversion to and from using same implementation class / interface. |
Beta Was this translation helpful? Give feedback.
I think your current setup looks valid. One thing on Jint's side is to consider if we need to make things a bit more obvious. Like allowing conversion to and from using same implementation class / interface.