[Cycle.js] Generalizing run() function for more types of sources

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[Cycle.js] Generalizing run() function for more types of sources相关的知识,希望对你有一定的参考价值。

Our application was able to produce write effects, through sinks, and was able to receive read effects, through the DOM sources. However, the main function only gets the DOMSource as input. This lessons shows how we can generalize main to receive an object of sources, containing all kinds of read effects that we can use.

 

Code to be chagned:

function run(mainFn, drivers) {
  const proxyDOMSource = new Rx.Subject();
  const sinks = mainFn(proxyDOMSource);
  const DOMSource = drivers.DOM(sinks.DOM);
  DOMSource.subscribe(click => proxyDOMSource.onNext(click));
//   Object.keys(drivers).forEach(key => {
//     drivers[key](sinks[key]);
//   });
}

 

This is hard code now, make it more fixable:

function run(mainFn, drivers) {

  const proxySource = {};

  //For each driver, we need to proxySource
  Object.keys(drivers).forEach( (key)=>{
    proxySource[key] =  new Rx.Subject();
  } );

  //Get sinks (output effect)
  const sinks = mainFn(proxySource);

  Object.keys(drivers).forEach( (key)=>{
    //for each drive, create a source for that
    const Source = drivers[key](sinks[key]);
    
    Source.subscribe( x => proxySource[key].onNext(x) );
  } );
}

 

---------------------

Code:

// Logic (functional)
function main(Sources) {
  const click$ = Sources.DOM;
  return {
    DOM: click$
      .startWith(null)
      .flatMapLatest(() => 
        Rx.Observable.timer(0, 1000)
         .map(i => `Seconds elapsed ${i}`)           
      ),
    Log: Rx.Observable.timer(0, 2000).map(i => 2*i),
  };
}

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

// bProxy = ...
// a = f(bProxy)
// b = g(a)
// bProxy.imitate(b)

function run(mainFn, drivers) {

  const proxySource = {};
  Object.keys(drivers).forEach( (key)=>{
    proxySource[key] =  new Rx.Subject();
  } );
  const sinks = mainFn(proxySource);
  Object.keys(drivers).forEach( (key)=>{
    const Source = drivers[key](sinks[key]);
    Source.subscribe( x => proxySource[key].onNext(x) );
  } );
}

run(main, drivers);

// source: input (read) effects
// sink: output (write) effects



// Effects (imperative)
function DOMDriver(text$) {
  text$.subscribe(text => {
    const container = document.querySelector(‘#app‘);
    container.textContent = text;
  });
  const DOMSource = Rx.Observable.fromEvent(document, ‘click‘);
  return DOMSource;
}

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

 

以上是关于[Cycle.js] Generalizing run() function for more types of sources的主要内容,如果未能解决你的问题,请参考以下文章

[Cycle.js] The Cycle.js principle: separating logic from effects

学习RxJS:Cycle.js

学习RxJS:Cycle.js

替换 cycle2.js 中的 <img> 标签

在 Cycle.js 中呈现所有 dom 后运行 js 代码

jQuery图片切换插件jquery.cycle.js