隔离组件实例
在上一节中,我们学会了怎么区分组件实例,最终是成功了,但是也带来了大量的人工劳动。Cycle.js 也意识到了这一点,为我们提供了一个 helper 函数 -- isolate()
,首先引入它:
<script src="https://rawgit.com/cyclejs/isolate/v1.1.1/dist/cycle-isolate.js"></script>
使用是非常简单的:
isolte(Component, scope);
scope
指定了组件的域,如果没有指定 scope
,Cycle.js 将随机生成 scope。
/* 固定scope */
<div class="label-slider cycle-scope-weight"></div>
/* 随机scope */
<div class="label-slider cycle-scope-cycle1"></div>
const isolate = CycleIsolate;
// ....
function main(sources) {
const WeightSlider = isolate(LabeledSlider, 'weight');
const weightProps$ = Rx.Observable.of({
label: 'Weight',
unit: 'kg',
min: 40,
max: 150,
init: 70
});
const weightSinks = WeightSlider({
DOM: sources.DOM,
props: weightProps$
});
const weightVTree$ = weightSinks.DOM;
const HeightSlider = isolate(LabeledSlider, 'height');
const heightProps$ = Rx.Observable.of({
label: 'Height',
unit: 'cm',
min: 140,
max: 220,
init: 170
});
const heightSinks = HeightSlider({
DOM: sources.DOM,
props: heightProps$
});
const heightVTree$ = heightSinks.DOM;
const vtree$ = Rx.Observable.combineLatest(
weightSinks.DOM, heightSinks.DOM,
(weightVTree, heightVTree) => {
return div([
weightVTree,
heightVTree
]);
}
);
return {
DOM: vtree$
};
}