Preview the project and you should see the "On before project start" message appear in the console.
Notice how:
- We have added a function named
OnBeforeProjectStart
which takes runtime
as a parameter.
- We use an arrow function for the function in
addEventListener
. This in turn just calls OnBeforeProjectStart(runtime)
, which passes along runtime
.
In short this means our OnBeforeProjectStart
function is called with runtime
when the "beforeprojectstart" event happens. Also note how we now have a short sequence of events: when loading the page, runOnStartup
will run its callback; that then waits for the "beforeprojectstart" event; when that fires it calls OnBeforeProjectStart
. This kind of pattern is common when handling events in JavaScript, so it's worth getting familiar with it.
Button click event
In the OnBeforeProjectStart
function, the runtime has finished loading, and now things like object types and instances can be accessed.
The first thing we want to do is detect when the button is clicked. As before we can get the first instance of the Button object in the layout with:
let buttonInst = runtime.objects.Button.getFirstInstance();
Once again instances use the addEventListener
method for handling events. In the IButtonInstance documentation it notes the "click" event fires when the button is clicked. So we can listen for click events like this (showing all the code for main.js):
runOnStartup(runtime =>
{
runtime.addEventListener("beforeprojectstart", () => OnBeforeProjectStart(runtime));
});
function OnBeforeProjectStart(runtime)
{
let buttonInst = runtime.objects.Button.getFirstInstance();
buttonInst.addEventListener("click", () => OnButtonClick(runtime));
}
function OnButtonClick(runtime)
{
console.log("Button clicked!");
}
Preview this project and you should see the console message appear when you click the button. This time we've done everything with JavaScript code only - no event sheet is involved!
Moving the sprite instance
The last piece of the puzzle is to actually move the sprite instance in the layout. This can be done the same way as before, just with our code now in the OnButtonClick
function:
function OnButtonClick(runtime)
{
let inst = runtime.objects.Sprite.getFirstInstance();
inst.x += 10;
}
Preview the project, and now the sprite will move to the right when you click the button. We've re-built what we had previously, but with pure code.