作为一名新手,我试图在列表中列出中的3项内容。但是代码也有错误。我制作了jsbin并将代码放在下面。
http://jsbin.com/labonut/10/edit?js,output
Problem:当我单击最后一个复选框时,它会添加新的复选框(我不想要),而旧的复选框不会更改它的" on /off“标签。还有,除了最后一个,完全没有反应。我做错什么了?
const xs = xstream.default;
const {div, span, input, label, makeDOMDriver} = CycleDOM;
function List(sources) {
sources.DOM
var vdom$ = xs.fromArray([
{text: 'Hi'},
{text: 'My'},
{text: 'Ho'}
])
.map(x => isolate(ListItem)({Props: xs.of(x), DOM: sources.DOM}))
.map(x => x.DOM)
.flatten()
.fold((x, y) => x.concat([y]), [])
.map(x => div('.list', x));
return {
DOM: vdom$
}
}
function ListItem(sources) {
const domSource = sources.DOM;
const props$ = sources.Props;
var newValue$ = domSource
.select('.checker')
.events('change')
.map(ev => ev.target.checked);
var state$ = props$
.map(props => newValue$
.map(val => ({
checked: val,
text: props.text
}))
.startWith(props)
)
.flatten();
var vdom$ = state$
.map(state => div('.listItem',[
input('.checker',{attrs: {type: 'checkbox', id: 'toggle'}}),
label({attrs: {for: 'toggle'}}, state.text),
" - ",
span(state.checked ? 'ON' : 'off')
]));
return {
DOM: vdom$
}
}
Cycle.run(List, {
DOM: makeDOMDriver('#app')
});发布于 2016-07-26 17:28:05
一个更短的变体。
第一行,获取项Dom流数组。
第2行,然后将流合并成一个流,并将元素包装到父div中。
function List(sources) {
var props = [
{text: 'Hi'},
{text: 'My'},
{text: 'Ho'}
];
var items = props.map(x => isolate(ListItem)({Props: xs.of(x), DOM: sources.DOM}).DOM);
var vdom$ = xs.combine(...items).map(x => div('.list', x));
return {
DOM: vdom$
}
}发布于 2016-07-26 05:30:36
在弗拉基米尔的回答的启发下,这里有一个他的答案的“老派”变体,并改进了我最初的答案:
function List(sources) {
const props = [
{text: 'Hi'},
{text: 'My'},
{text: 'Ho'}
];
var items = props.map(x => isolate(ListItem)({Props: xs.of(x), DOM: sources.DOM}).DOM);
const vdom$ = xs.combine.apply(null, items)
.map(x => div('.list', x));
return {
DOM: vdom$
};
}旧式JSBin演示
(原答案)
问题似乎在您的List函数中。坦白地说,我不知道原因,但我想出了另一个解决办法:
function List(sources) {
const props = [
{text: 'Hi'},
{text: 'My'},
{text: 'Ho'}
];
function isolateList (props) {
return props.reduce(function (prev, prop) {
return prev.concat(isolate(ListItem)({Props: xs.of(prop), DOM: sources.DOM}).DOM);
}, []);
}
const vdom$ = xs.combine.apply(null, isolateList(props))
.map(x => div('.list', x));
return {
DOM: vdom$
};
}JSBin演示
这里的一个不同之处是,我没有在props对象中流项目。相反,我将数组传递给reduce作为支持的函数,将其传递给列表项vdom流的数组,然后将该数组传递给https://github.com/staltz/xstream combine工厂。
https://stackoverflow.com/questions/38577836
复制相似问题