cyclejs 在映射操作期间从输入文本中提取目标


Main.ts
const clickMessages$ = sources.DOM
.select('.add')
.events('click');
const latitudeMinimum$ = sources.DOM
.select('.latitudeMinimum')
.events('input');
const latitudeMaximum$ = sources.DOM
.select('.latitudeMaximum')
.events('input');

const latituteRange$ = xs.combine(latitudeMinimum$, latitudeMaximum$); 
const newStream$ = xs.combine(clickMessages$, latituteRange$);
const filter$ = newStream$.filter(c => { return true });
const map$ = filter$.map(([a, [b, c]]) => { return [b.target.value, c.target.value] } 
// <<--- b.target.value won't compile... was expecting to get my value from input field

问题是,DOM 事件的targetEventTarget类型,正如你在这里看到的 https://github.com/Microsoft/TypeScript/blob/master/src/lib/dom.generated.d.ts#L3661 泛型EventTarget类型只有几个方法。

在您的情况下,您确切地知道目标中将包含哪种元素。 因此,为了告诉编译器您的target具有value属性,您需要将其转换为更具体的类型(例如 https://github.com/Microsoft/TypeScript/blob/master/src/lib/dom.generated.d.ts#L5248 的 HTMLInputElement

我认为你不能一次做到这一点(或者至少我不知道有什么技术可以做到这一点(,所以你需要另一个map.

const latitudeMinValue$ = latitudeMinimum$
.map(event => event.target)
.map((element: HTMLInputElemnet) => element.name)
const latitudeMaxValue$ = latitudeMaximum$
.map(event => event.target)
.map((element: HTMLInputElemnet) => element.name)
const latituteRange$ = xs.combine(latitudeMinValue$, latitudeMaxValue$)
.map(/*([minValue, maxValue])*/); 

一种更干净的方法来执行此操作(因为我们重复map().map()两次,所以我们不是很干燥(,我们可以使用xstream给出的compose运算符。

function eventToTargetValue(event$ Stream<Event>) {
return event$.map(event => event.target)
.map((element: HTMLInputElement) => element.value)
}
const latitudeMinValue$ = latitudeMinimum$
.compose(eventToTargetValue)
const latitudeMaxValue$ = latitudeMaximum$
.compose(eventToTargetValue)
const latituteRange$ = xs.combine(latitudeMinValue$, latitudeMaxValue$)
.map(/*([minValue, maxValue])*/); 

希望对:)有所帮助

最新更新