Example

A simple counter application demonstrating basic state management and event handling in Now.js

Live Demo

-

Source Code


// Count Component
Now.getManager('component').define('count', {
  // Reactive enabled
  reactive: true,

  // Component state
  state: {
    title: 'Count Component',
    count: 0
  },

  // Component methods
  methods: {
    increment() {
      this.state.count++;
      console.log('increment', this.state.count);
    },
    decrement() {
      this.state.count--;
      console.log('decrement', this.state.count);
    },
    reset() {
      this.state.count = 0;
      console.log('reset', this.state.count);
    },
  },

  // Lifecycle hooks
  mounted() {
    console.log('Count component mounted');
  },

  // Event handlers - will be properly handled now
  events: {
    'app:cleanup:end': function() {
      this.state.count = 0;
      console.log('app:cleanup:end', this.state.count);
    }
  }
});
                

<div class="counter-app">
  <div class="counter-display">
    <span class="counter-number" data-text="count"></span>
  </div>
  <div class="counter-controls">
    <button class="button blue large" data-on="click:decrement">-</button>
    <button class="button blue large" data-on="click:increment">+</button>
  </div>
  <button class="button green" data-on="click:reset">Reset</button>
</div>

.counter-app {
  text-align: center;
  padding: var(--spacing-8);
}
.counter-display {
  font-size: 4rem;
  font-weight: bold;
  margin-bottom: var(--spacing-8);
}
.counter-controls {
  display: flex;
  gap: var(--spacing-4);
  justify-content: center;
  margin-bottom: var(--spacing-4);
}
.counter-number {
  font-family: var(--font-family-mono);
  color: var(--color-primary);
}
                

How it Works

State Management

The counter uses Now.js state management to track the count value. When state changes, the component automatically updates the display.

Event Handling

Click events are handled using data-on attributes that map to component methods. This demonstrates Now.js's declarative event binding.

Data Binding

The data-text directive automatically updates the display when the count changes, showing Now.js's reactive data binding system.

Component Lifecycle

The component manages its own state and cleanup, demonstrating proper component lifecycle management.

Next Steps