Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

153
Vistas
Stencil.js - Separate concerns between UI & Logic

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.

about 4 years ago · Juan Pablo Isaza
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda