4. run() 函数及 drivers
上一节中,逻辑和外部环境的绑定我们是手动完成的:
const sink = main();
DOMEffect(sink.DOM);
consoleLogEffect(sink.Log);
现在,我们给定一个逻辑和外部环境的映射关系:
const effects = {
DOM: DOMEffect,
Log: consoleLogEffect
};
就可以通过定义一个 run()
方法自动完成逻辑和外部对象的绑定:
function run(main, effects) {
const sink = main;
Object.keys(effects).forEach(key => {
effects[key](sink[key]);
});
}
driver(驱动)是沟通硬件和软件的桥梁,有中介的意味,因此,把 effects
对象命名为 drivers
更加贴切。drivers[logic]
的值就表述了逻辑 logic
对应的外部对象:
function main() {
return {
DOM: Rx.Observable.timer(0, 1000)
.map(i => `Seconds Elapsed ${i}`),
Log: Rx.Observable.timer(0, 2000)
.map(i => 2 * i)
};
}
function DOMDriver(text$) {
text$.subscribe(text => {
$app = document.querySelector('#app');
$app.textContent = text;
});
}
function consoleLogDriver(msg$) {
msg$.subscribe(msg => {
console.log(msg);
});
}
const drivers = {
DOM: DOMDriver,
Log: consoleLogDriver
};
function run(main, drivers) {
const sink = main();
Object.keys(drivers).forEach(key => {
drivers[key](sink[key])
});
}
run(main, drivers);
const sink = main();
DOMDriver(sink.DOM);
consoleLogDriver(sink.Log);