2017-04-19 30 views
1

余米试图创建一个数组的地图运营商的内部日志流,但似乎不顺心的事在我的代码,我不能指出来......Cyclejs和西河不显示任何

import {Slider} from './slider/slider' 
import xs from 'xstream' 

export function App(sources) { 
    const props = { 
     marbles$: xs.fromArray([{ 
      color: 'red', 
      x: 0 
     }, { 
      color: 'blue', 
      x: 20 
     }]) 
    } 

    props.marbles$.map(item => { 
     console.log(item) // nothing displayed on here 
     return item 
    }) 
    return Slider(Object.assign(sources, {props})) 
} 

在这个小代码中,我简单地创建一个包含从数组中的弹珠$流的道具对象。

就在下面我尝试登录流中的每个项目,但没有任何反应,我不明白为什么。


Plunker这里:https://plnkr.co/edit/6uMsLIl1Edd5x670OqHa?p=preview

没有显示HTML文件,只在JS文件

任何想法?

回答

1

正如xstream文档说明,直到他们得到他们的第一个listener,它与addListener方法来实现流是空闲(不执行)。

请注意,props.marbles$.map流被分配给变量y。然后调用y.addListener方法。当调用addListener时,最终执行props.marbles$.map方法。

const props = { 
    marbles$: xstream.Stream.fromArray([{ 
    color: 'red', 
    x: 0 
    }, { 
    color: 'blue', 
    x: 20 
    }]) 
} 

const y = props.marbles$.map(item => { 
    console.log('map', item) 
    return item 
}) 

y.addListener({}) 

输出在控制台:

map > Object {color: "red", x: 0} 
map > Object {color: "blue", x: 20} 

或者你可以把console.log的听众,而不是map方法的next属性:

const y = props.marbles$.map(item => { 
    return item 
}) 

y.addListener({ 
    next: item => console.log('listener', item) 
}) 

在产出控制台:

listener > Object {color: "red", x: 0} 
listener > Object {color: "blue", x: 20} 

,或者如André suggested,你可以使用XStream的debug

const props = { 
    marbles$: xstream.Stream.fromArray([{ 
    color: 'red', 
    x: 0 
    }, { 
    color: 'blue', 
    x: 20 
    }]).debug('debug 1') 
} 

const y = props.marbles$.map(item => { 
    return item 
}).debug('debug 2') 

y.addListener({}) 

输出在控制台:

debug 1 > Object {color: "red", x: 0} 
debug 2 > Object {color: "red", x: 0} 
debug 1 > Object {color: "blue", x: 20} 
debug 2 > Object {color: "blue", x: 20} 
2

如果您在不捕获输出的情况下致电props.marbles$.map(....),您将创建一个简单地放在地板上而不会使用的流。因为这只是函数式编程,所以与const y = Math.round(x)一样,但编写为Math.round(x)。它将采用数字x,返回四舍五入到最接近的整数,并放弃结果。

由于您只想用控制台调试该值,因此我建议使用xstream运算符debug()。只需将它添加到运营商的链条:如果你使用一些掉毛工具,如https://github.com/bodil/eslint-config-cleanjs

const props = { 
    marbles$: xs.fromArray([{ 
     color: 'red', 
     x: 0 
    }, { 
     color: 'blue', 
     x: 20 
    }]).debug() 
} 

,它会提醒您未使用的返回值的声明。

+0

但我应该在地图功能通过对每一个项目,即使我什么都没做对吗?我可能误解了一件事情。我只需要检查我的流中现在的内容,没有别的,调试目的 – mfrachet