I have a button '#btn1' in a repeater. There are 2 ways to handle a click event for that button.
1) From the event handlers panel on the right, create a binding for the #btn1 which will create a export function btn1_click(). This is probably the usual method for handling most events.
2) Or handle it inside the $w.onReady() as follows:
$w.onReady(function () {
...
$w("#btn1").onClick((event) => {
...
})
})
This is somewhat unusual but works for some reason. I do not fully understand the logic behind it even though I have used this method in the code.
My first question is: What is the difference between the 2 methods and which one is the preferred method for use in repeaters?
My second question is: Does the $w.onReady() get called every time I click on something on the page? If not how does it know to reach the onClick() code when I click on something?
Both methods are equivalent. All they do is define the function (event handler) to be called when an event is triggered.
The $w.onReady() function is called once, when the page is ready. If the onClick() code is defined in the onReady() function, then that means the onClick() code is defined for the page, and will be invoked whenever the onClick event is triggered for that element.
For more information about the page onReady() function, see the following:
$w.onReady() :: a guide for the perplexed
$w.onReady() API