[Cycle.js] Introducing run() and driver functions

Currently the code looks like :

复制代码
// Logic (functional)
function main() {
  return {
    DOM: Rx.Observable.timer(0, 1000)
      .map(i => `Seconds elapsed ${i}`),
    Log: Rx.Observable.timer(0, 2000).map(i => 2*i),
  };
}

// Effects (imperative)
function DOMEffect(text$) {
  text$.subscribe(text => {
    const container = document.querySelector('#app');
    container.textContent = text;
  });
}

function consoleLogEffect(msg$) {
  msg$.subscribe(msg => console.log(msg));
}

const sinks = main();
DOMEffect(sinks.DOM);
consoleLogEffect(sinks.Log);
  
复制代码

 

We still have this part of code which didn't wrap into a function, we can wrap into a run() function, this can provide a main enterence for the code:

function run(mainFn){
  const sinks = mainFn();
  DOMEffect(sinks.DOM);
  consoleLogEffect(sinks.Log);
}

run(main);

 

Let's say we want to remove consoleLogEffect, current way we need to comment out from the main() function. 

The problems are that in the first place we are hard coding these effects inside run. Instead, we should be able to specify that these are the effects that I want to run my main function, so we need to give our effects to run as well.

That will be an object. Effects functions will be an object, and the keys will match those keys that we saw from the sync here. The DOM function is DOM Effect, and the log function is consoleLogEffect.

复制代码
const effects = {
    DOM: DOMEffect,
    Log: consoleLogEffect
}

function run(mainFn, effects){
  const sinks = mainFn();
  Object.keys(effects)
    .forEach( (effectKey)=>{
    effects[effectKey](sinks[effectKey]);
  })
}

run(main, effects);
复制代码

 

The last thing author introduce the 'driver' as the name instead of 'effect' ...

复制代码
// Logic (functional)
function main() {
  return {
    DOM: Rx.Observable.timer(0, 1000)
      .map(i => `Seconds elapsed ${i}`),
    Log: Rx.Observable.timer(0, 2000).map(i => 2*i),
  };
}

// Effects (imperative)
function DOMDriver(text$) {
  text$.subscribe(text => {
    const container = document.querySelector('#app');
    container.textContent = text;
  });
}

function consoleLogDriver(msg$) {
  msg$.subscribe(msg => console.log(msg));
}

function run(mainFn, drivers) {
  const sinks = mainFn();
  Object.keys(drivers).forEach(key => {
    drivers[key](sinks[key]);
  });
}

const drivers = {
  DOM: DOMDriver,
  Log: consoleLogDriver,
}

run(main, drivers);

  
复制代码

 

posted @   Zhentiw  阅读(250)  评论(0编辑  收藏  举报
(评论功能已被禁用)
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
点击右上角即可分享
微信分享提示