Cycle.js - 如何获取集合项中的集合长度

时间:2018-06-13 02:26:14

标签: javascript functional-programming cyclejs

我正在尝试将一些行为专门添加到Cycle.js列表中的最后一项。我尝试使用cycle-onionify来制作这样的集合:

string2

据我所知,镜头可用于在组件之间共享状态,但似乎没有办法将镜头与系列配合使用。我想我可以将收集长度传递给孩子,所以我可以将它与id进行比较。

我有什么遗失的吗?

1 个答案:

答案 0 :(得分:2)

您可以使用makeCollection的镜头。记住它会返回一个可以隔离的正常Cycle.js组件。因此,如果你想添加一个布尔isLast,你可以这样做:

function omit(obj, key) {
    let tmp = { ...obj }; //Copy the object first
    delete tmp[key];
    return tmp;
}

const listLens = {
   get: stateArray => stateArray.slice(0, -1).concat({
            ...stateArray[stateArray.length - 1],
            isLast: true
        }),
   set: (stateArray, mappedArray) => mappedArray.slice(0, -1)
           .concat(omit(mappedArray[mappedArray.length - 1], 'isLast'))
};

const List = isolate(
    makeCollection({
        item: Child,
        itemKey: (childState, index) => String(index),
        itemScope: key => key,
        collectSinks: instances => ({
            onion: instances.pickMerge('onion'),
            DOM: instances.pickCombine('DOM')
                .map(itemVNodes => ul(itemVNodes))
        })
    }),
    { onion: listLens, '*': null }
);

作为旁注,如果您想在每个单独的项目上应用镜头,您也可以使用itemScope属性。例如

itemScope: key => ({ onion: myLens, '*': key })