@composi/runtime:
Efectos
Managing Effects in a Program
Some code in a project will create side effects. This might be data manipulation, code that runs asynchronously and fetches data or manages a looping poll, setup of a websocket, or changes the visual appearance of an element in the DOM. @composi/core's runtime has three ways of implementing effects: actions
, subscriptions
and lifecycle hooks
.
Acciones
The main way that you will deal with effects are through actions. These are triggered when they receive a message. There are three possible origins for a message: when a user interacts with the View, an event can send a message that gets processed by an action, an action can send a message to another action, and a subscription can send a message to an action. Learn more about actions in the documentation for update.Susripciones
If you need to run code when your program starts, you need to use subsriptions. Usually this will be fore fetching data, setting up a looping poll, create a web socket or web service. When you get a result that you want to make available to your program you can send a message to an action to do so. Learn more about subscrition in its docs.
Enganches de Ciclo de Vida
@composi/core implements three lifecycle hooks. These work differently from React in that they get registered on the
element you want to track. There are three lifecycle hooks: onmount, onupdate and onunmount. These enable you to
implement visual effects on DOM elements. You would use these to do something like hide or show elements or animate
them. Examples of when to use them: you would use onmount
to animate a item added to a list; use
onupdate
to set focus on an input element; use onunmount
to animate an item when removed
from a list. Lifecycle hooks make it easy to implement visual effects for the elements in your program's view. Learn
more about lifecycle hooks in the documentation.
Un Programa Que Sólo Tiene Efectos
A continuación se muestra un ejemplo de un programa de entorno de ejecución que tiene dos efectos pero no devuelve una vista. En cambio, la función view devuelve undefined (indefinido). El inicio de este programa tiene estado y efecto. El efecto hace que un contador se inicie en el tiempo de carga. Cuando llega a cinco, activa otro efecto para alertar el resultado final. Si abre la consola del inspector web, verás el progreso del conteo, seguido de una alerta al finalizar.
See the Pen @composi/core + runtime Efectos-1 by Robert Biggs (@rbiggs) on CodePen.
When your program is very simple it may not seem like such a big deal to separate effects into separate spheres. But as a program becomes more complex, implementing actions, subscriptions and lifecycle hooks results in code that is easier to reason about and maintain. State management goes in actions, startup async code goes in subscriptions, visual effects get handled by lifecycle hooks.
Cuando tu programa es muy sencillo, puede que no parezca tan importante separar los efectos de la otra lógica. Pero a medida que un programa se vuelve más complejo, el aislamiento de los efectos de la lógica de negocios da como resultado un código más fácil de razonar.
batch
Sometimes you may have several effects that you need to run together. Or you have one big effect doing alot of things that you want to break down into smaller pieces. @composi/core provides batch
for these purposes. It allows you to create a map of effects that you can execute one after the other. Be aware that effects run asynchronously and independently of each other. So, event though they are being executed in order, they will probably terminate at different times. If you want to execute effects sequentially, one after the other, then you should look into running them as ES6 async/await functions.
A veces puedes tener muchos efectos que necesitas ejecutar juntos. O tienes un efecto bien complejo haciendo muchas cosas que quieres dividir en pedazos más pequeños. @composi/core proporciona batch
para esos propósitos. Te permite crear una matriz de efectos que puedes ejecutar uno tras otro. Ten en cuenta que los efectos se ejecutan de forma asíncrona e independiente entre sí. Por eso, aunque los eventos se están ejecutando en orden, probablemente terminarán en diferentes momentos. Si deseas ejecutar los efectos de forma secuencial, uno tras otro, deberías considerar ejecutarlos como funciones asincrónicas, usando async/await de ES6.
El ejemplo siguiente muestra cómo combinar los efectos. Abre la consola del navegador para ver el resultado de los tres efectos.
See the Pen @composi/core + runtime Efectos by Robert Biggs (@rbiggs) on CodePen.