Skip to content

JSObject Base Class

JSObjects are wrappers around IJSInProcessReference objects that can be passed to and from Javascript and allow strongly typed access to the underlying object.

Over 300 JSObject wrapped Javascript objects are included in SpawnDev.BlazorJS. JSObject wrappers are easy to create and use. Request a library wrapper by opening an issue on our GitHub repo.

Below shows a section of the SpawnDev.BlazorJS.JSObjects.Window class. Window's base type, EventTarget, inherits from JSObject.

public class Window : EventTarget {
    // all JSObject types must have this constructor
    public Window(IJSInProcessObjectReference _ref) : base(_ref) { }
    // here is a property with both getter and setter
    public string? Name { get => JSRef.Get<string>("name"); set => JSRef.Set("name", value); }
    // here is a read only property that returns another JSObject type
    public Storage LocalStorage => JSRef.Get<Storage>("localStorage");
    // here are methods
    public void Alert(string msg = "") => JSRef.CallVoid("alert", msg);
    public long SetTimeout(Callback callback, double delay) => JSRef.Call<long>("setTimeout", callback, delay);
    public void ClearTimeout(long requestId) => JSRef.CallVoid("clearTimeout", requestId);    
    // here is an event that can used with += and -=
    public JSEventCallback<StorageEvent> OnStorage { get => new JSEventCallback<StorageEvent>("storage", AddEventListener, RemoveEventListener); set { } }
    // ... 
}

Below the Window class is used

// below the JSObject derived Window class is used
using var window = JS.Get<Window>("window");
var randName = Guid.NewGuid().ToString();
// set and get defined properties
window.Name = randName;
var name = window.Name;
// call methods
window.Alert("Hello!");
// attach events
window.OnStorage += Window_OnStorage;
// or attach using addEventListener
window.AddEventListener<StorageEvent>("storage", Window_OnStorage);
// set custom property on window
window.JSRef.Set("fruit", "apples");
// read a custom property on window
var fruit = window.JSRef.Get<string>("fruit");
...

// Window_OnStorage definition
void Window_OnStorage(StorageEvent e){

}

Custom JSObjects

Implement your own JSObject classes for Javascript objects not already available in the BlazorJS.JSObjects library.

Instead of this (simple but not as reusable)

var audio = JS.New("Audio", "https://some_audio_online");
audio.CallVoid("play");
You can do this...
Create a custom JSObject wrapper
public class Audio : JSObject
{
    public Audio(IJSInProcessObjectReference _ref) : base(_ref) { }
    public Audio(string url) : base(JS.New("Audio", url)) { }
    public void Play() => JSRef.CallVoid("play");
}

Then use your new object

var audio = new Audio("https://some_audio_online");
audio.Play();