On top of the events detailed in Life Cycle of jsRO Objects, events can be created in the application that are defined by the programmer and when fired will be propagated from the application to the browser.
The following example shows how to add a personalized event to an object and how this can be handled from Javascript. In this case we'll expose, as a JSON, the mouse coordinates.
Definition and use of an event in Delphi:
// Creates the remote object
FRo := TJSObject.Create('ro');
// Adds the event
FRo.Events.Add('mousePositionChanged')
.AddArgument('coords', JSDT_JSON); // Adds the mouse position as JSON
FRo.ApplyModel;
procedure TForm1.FormMouseMove(Sender: TObject; Shift: TShiftState;
X, Y: Integer);
begin
FRo.Events['mousePositionChanged']
.ArgumentAsJSON('coords', '{"x": ' + X + ', "y": ' + Y + '}')
.Fire;
end;
Definition and use of an event in .Net:
// Creates the remote object
ro = new JSObject("ro");
// Adds the event
ro.Events.Add("mousePositionChanged")
.AddArgument("coords", IJSDataType.JSDT_JSON) // Adds the mouse position as JSON
ro.ApplyModel();
...
...
private void Form1_MouseMove(object sender, MouseEventArgs e)
{
ro.Events["mousePositionChanged"]
.ArgumentAsJSON("coords",
"{ \"x\": " + MousePosition.X + ", \"y\": " + MousePosition.Y + "}")
.Fire();
}
Definition and use of an event in C#:
// Creates the remote object
ro = new JSObject("ro");
// Adds the eventro.Events.Add("mousePositionChanged")
.AddArgument("coords", IJSDataType.JSDT_JSON) //the mouse position as JSON
ro.ApplyModel();
...
...
private void Form1_MouseMove(object sender, MouseEventArgs e)
{ ro.Events["mousePositionChanged"]
.ArgumentAsJSON("coords", "{ \"x\": " + MousePosition.X + ", \"y\": " + MousePosition.Y + "}")
.Fire();
}
To handle the event in Javascript, please note that the Javascript syntax for the personalized events differs slightly from the syntax for the model events, since it's declared directly associated to the name of the jsRO (without the "model"):
jsro.on('ro', 'mousePositionChanged', function (coords) {
console.log('mouse moved to [' + coords.x + ', ' + coords.y + ']');
});