我创建了一个类foo的元素。然后我打算在发生单击事件后将其类与bar交换。但是,当我单击元素时,订阅了foo和bar的单击事件的流被连续触发。结果,元素的类没有改变。如何订阅其类随时间变化的同一元素的事件?
这是链接:
https://jsbin.com/kanomonexa/edit?html,js,控制台,输出
这是示例代码:
const {div, button, makeDOMDriver} = CycleDOM;
const toggleDriver = (data$)=> {
data$.subscribe(function(data) {
if (data.operation === 'remove' ) {
$(data.selector).removeClass(data.className);
}
else if (data.operation === 'add') {
$(data.selector).addClass(data.className);
}
else {
$(data.selector).toggle(data.className);
}
});
return Rx.Observable.empty();
};
const consoleLogDriver = (data$)=>{
data$.subscribe(data=> {
console.log(data);
});
return Rx.Observable.empty();
};
const main = (sources) =>{
const fooClick$ = sources.DOM
.select('.foo')
.events('click');
const fooLog$ = fooClick$.map(_ =>'.foo is Clicked');
const toggleFoo$ = fooClick$.flatMap(_ => {
const result = [
{
operation: 'remove',
selector: 'button',
className: 'foo'
},
{
operation: 'add',
selector: 'button',
className: 'bar'
}
];
return Rx.Observable.fromArray(result);
});
const barClick$ = sources.DOM
.select('.bar')
.events('click');
const barLog$ = barClick$.map(_ => '.bar is Clicked');
const toggleBar$ = barClick$.flatMap(_ =>{
const result = [
{
operation: 'remove',
selector: 'button',
className: 'bar'
},
{
operation: 'add',
selector: 'button',
className: 'foo'
}
];
return Rx.Observable.fromArray(result);
});
const log$ = Rx.Observable.merge(
fooLog$,
barLog$
);
const toggle$ = Rx.Observable.merge(
toggleFoo$,
toggleBar$
);
const vTree$ = Rx.Observable.of(div([
button('#button.foo',['Click me'])
]));
return {
DOM: vTree$,
consoleLogDriver: log$,
toggleDriver:toggle$
};
};
var drivers = {
DOM: makeDOMDriver('#app'),
toggleDriver: toggleDriver,
consoleLogDriver: consoleLogDriver
};
Cycle.run(main, drivers);
<!DOCTYPE html>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/4.0.6/rx.all.js"></script>
<script src="https://code.jquery.com/jquery-2.1.4.js"></script>
<script src="https://rawgit.com/cyclejs/cycle-core/v6.0.3/dist/cycle.js"></script>
<script src="https://rawgit.com/cyclejs/cycle-dom/v9.4.0/dist/cycle-dom.js"></script>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<div id="app"></div>
</body>
</html>