Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

156
Visualizações
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 à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda