Stencil.js - Separate concerns between UI & Logic

Viewed 101

This question is inspired by the convention of Using React Hooks to Separate Concerns.

Would it be possible to incorporate a similar system using Stencil?

This is the initial idea, it is inspired by Angular's Services convention:

1. Create Regular Stencil component:

import { Component, State, h } from '@stencil/core';

@Component({
  tag: 'my-app-component'
})

export class MyAppComponent {
  @State() color: string = 'blue';

  private changeColorToRed() {
    this.color = 'red';
  }

  private changeColorToBlue() {
    this.color = 'blue';
  }

  render() {
    return (
      <div>
        <button onClick={this.changeColorToRed}>Red</button>
        <button onClick={this.changeColorToBlue}>Blue</button>
        <p>Selection: {this.color}</button>
      </div>
    );
  }
}

2. Separate methods in MyAppService.ts:

export default class MyAppService {
  color: string;

  constructor({ color }) {
    this.color = color;
  }

  changeColorToRed() {
    this.color = 'red';
  }

  changeColorToBlue() {
    this.color = 'blue';
  }
}

3. Modify Stencil component, replace methods with Service:

import { Component, State, h } from '@stencil/core';

import MyAppService from './MyAppService.ts';

@Component({
  tag: 'my-app-component'
})

export class MyAppComponent {
  private service;

  @State() color: string = 'blue';

  connectedCallback() {
    this.service = new MyAppService({ color: this.color }); 
  }

  render() {
    return (
      <div>
        <button onClick={this.service.changeColorToRed}>Red</button>
        <button onClick={this.service.changeColorToBlue}>Blue</button>
        <p>Selection: {this.color}</button>
      </div>
    );
  }
}

While this may work for a simple example, I am unsure whether this is the right convention for this, and I am not confident that reactivity is preserved since I am only initializing the Service in connectedCallback.

I am looking to find out if there is a better way of doing this, any obvious reasons why this won't work that I might have overlooked, and any similar ideas which could declutter the JSX & Logic code.

0 Answers
Related