Event Handlers
HTML Event Attributes
When using the Cog library with JavaScript modules, functions defined inside a module are not automatically available in the global scope. This means that they cannot be directly used as event handlers in your HTML, as the HTML only has access to the global scope.
Using Global Scope
You can explicitly add your functions to the global window
object, which will make them available in the global scope and therefore usable as event handlers in your HTML.
// In your JavaScript module
function increment() {
counter.set(counter.value + 1);
}
// Add the function to the global window object
window.increment = increment;
Now, you can use increment
as an onclick
handler in your HTML:
<button onclick="increment()">Increment</button>
This way, even though you're using modules, you can still use your functions as event handlers in your HTML.
Without Global Scope
When using JavaScript modules, you can avoid adding your functions to the global scope by implementing your own event listeners and handlers. This can be done by using document.querySelector
or similar methods to get the HTML element, and then defining your own callbacks.
import { variable } from "@mzrk/cog";
const counter = variable("counter", 0);
function increment() {
counter.set(counter.value + 1);
}
// Get the button element
const button = document.querySelector("button");
// Add an event listener to the button
button.addEventListener("click", increment);
In this example, we're using document.querySelector
to get the button element from the HTML. We then use addEventListener
to add a 'click' event listener to the button. The increment
function will be called whenever the button is clicked.
This way, you can use your functions as event handlers without adding them to the global scope.
Event Handlers in Cog
Cog introduces a custom syntax for event handlers that allows you to avoid polluting the global scope with functions. Instead of using built-in HTML event attributes like onclick
, you can use Cog's data-on-[event]
syntax.
For example, instead of writing:
<button onclick="increment()">Increment</button>
And having to attach increment
to the global window object:
window.increment = function () {
// Your code here
};
You can use Cog's custom syntax:
<button data-on-click="increment">Increment</button>
And define increment
using Cog's variable
function:
variable("increment", () => {
// Your code here
});
With this approach, the increment
function is not added to the global scope. Instead, Cog will look for a function named increment
in the state defined by the variable
function when the button is clicked.
This approach keeps your global scope clean and makes your code easier to manage.