Skip to content

Counter

Ein einfacher Counter zum Demonstrieren von State-Management in Islands.

Component HTML

html
<div class="max-w-md mx-auto">
  <h2 class="text-2xl font-bold text-gray-900 mb-6">{{title}}</h2>

  <div
    data-island="counter"
    data-island-props='{"initialCount": {{initialCount}}}'
  >
    <!-- Counter Island rendert hier -->
  </div>
</div>

Island Code

javascript
// islands/counter.js
export default class CounterIsland {
  constructor(element, props = {}) {
    this.element = element;
    this.count = props.initialCount || 0;
    this.init();
  }

  init() {
    this.render();
    this.attachEvents();
  }

  render() {
    this.element.innerHTML = `
      <div class="p-6 bg-white rounded-lg border border-gray-200">
        <div class="flex items-center justify-center gap-4 mb-4">
          <button
            class="decrement px-4 py-2 bg-gray-600 text-white rounded hover:bg-gray-700 transition-colors"
            aria-label="Decrement"
          >
            -
          </button>
          <span class="count-display text-4xl font-bold text-gray-900 min-w-[3rem] text-center">
            ${this.count}
          </span>
          <button
            class="increment px-4 py-2 bg-blue-600 text-white rounded hover:bg-blue-700 transition-colors"
            aria-label="Increment"
          >
            +
          </button>
        </div>
        <button
          class="reset w-full px-4 py-2 bg-gray-200 text-gray-700 rounded hover:bg-gray-300 transition-colors"
        >
          Reset
        </button>
      </div>
    `;
  }

  attachEvents() {
    this.element.querySelector('.increment').addEventListener('click', () => {
      this.count++;
      this.updateDisplay();
    });

    this.element.querySelector('.decrement').addEventListener('click', () => {
      this.count--;
      this.updateDisplay();
    });

    this.element.querySelector('.reset').addEventListener('click', () => {
      this.count = 0;
      this.updateDisplay();
    });
  }

  updateDisplay() {
    const display = this.element.querySelector('.count-display');
    display.textContent = this.count;
  }

  destroy() {
    // Cleanup wenn component entfernt wird
  }
}

Was du lernst

  • State Management: Reaktive Variablen verwalten
  • Event Handling: Button-Clicks verarbeiten
  • DOM Updates: UI basierend auf State aktualisieren
  • Framework-Vergleich: Unterschiede zwischen Vanilla JS, Svelte, React und Vue

Webmate Studio Component Development Dokumentation