Skip to main content

Counter

Render a button that when clicked, increments a value.

Features used in this example:

  • Reading and writing values to properties (context.get and context.set).
  • Render View elements using different frameworks.

Example

 

Simple counter button example without using any external libraries.

manifest.yaml
name: Counter (JavaScript)
description: An example using JavaScript and no framework to render a simple button that displays the number of times the button is clicked.
categories: starter/javascript,starter/vanilla
keywords: starter,javascript,vanilla,counter
icon: logos:javascript
environments: browser
sandbox: browser.shadow
properties.yaml
view:
datatype: web-view
count:
datatype: number
description: The number of times the button has been clicked since this application was started. This represents using a simple Property in the Openexus system.
default: 1
src/main.js
/**
* An example using JavaScript and no framework to render a simple
* button that displays the number of times the button is clicked.
*/

let button;

// Define a render function to return our HTMLElement to display.
function render() {
// Create the element.
button = document.createElement('button');

// Populate the element.
button.innerHTML = `Count is ${context.get('count')}`;

// Openexus components use tailwind by default, but you can define CSS
// classes and styles in your preferred manner.
button.classList.add('bg-blue-500', 'hover:bg-blue-700', 'text-white', 'py-2', 'px-4', 'rounded');

// For our button we want to mutate our count state when it is clicked.
button.addEventListener('click', (value) => {
context.set('count', context.get('count') + 1);
});

return button;
}

// Register to be notified when ((count)) changes.
context.subscribe('count', (value) => {
if (button) button.innerHTML = `Count is ${value}`;
});

// Set our render function to the ((view)) property for rendering.
context.set('view', context.render(render));