-
Notifications
You must be signed in to change notification settings - Fork 3
How to expose dotnet functionality to BaristaCore scripts.
There are currently a few ways of exposing native .net functionality to Barista scripts:
By using the JsValue derived objects, one can manually create the corresponding JavaScript objects
For example, within a custom Barista Module:
[BaristaModule("adder", "The answer is...")]
public class AdderModule : IBaristaModule
{
public Task<object> ExportDefault(BaristaContext context, BaristaModuleRecord referencingModule)
{
var fnAdd = ctx.CreateFunction(new Func<JsObject, int, int, int>((thisObj, a, b) =>
{
return a + b;
}));
return Task.FromResult<object>(fnAdd);
}
}
Another other way is to export an object, BaristaCore with automatically convert the object to a JavaScript object.
[BaristaModule("native-object", "Returns a native .net object that can be used within scripts.")]
public class NativeObjectModule : IBaristaModule
{
public Task<object> ExportDefault(BaristaContext context, BaristaModuleRecord referencingModule)
{
var foo = new CarlyRae() { Name = "Kilroy" };
return Task.FromResult<object>(foo);
}
}
Types can be directly exported as well and are converted to JavaScript prototypes.
This probably deserves a whole entire section on the conversion process. However, for right now:
Classes => JS Constructor Function
Static Properties => properties defined on the constructor
Static Methods => functions defined on the constructor
Static Events => adds static addEventListener/removeEventListener/removeAllEventListeners on the constructor
Instance Properties -> properties defined on the prototype
Methods => functions defined on the prototype
Events => adds static addEventListener/removeEventListener/removeAllEventListeners to the prototype.
Classes marked as IEnumerable expose a Symbol.iterator property on the prototype as described in the JavaScript iteration protocol
A number of attributes control the conversion process:
[BaristaIgnore] => ignore the property/method/event
[BaristaProperty(string name, enumerable, configurable, writable)] => define the name and how the property is exposed.
The two mentioned techniques can be combined for maximum effect. See the fetch module for an example of this.