patrick
patrick

Reputation: 16969

cyclejs extract target from input text during map operation

 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

Upvotes: 0

Views: 224

Answers (1)

atomrc
atomrc

Reputation: 2583

The thing is, the target of a DOM event is of type EventTarget as you can see here https://github.com/Microsoft/TypeScript/blob/master/src/lib/dom.generated.d.ts#L3661 The generic EventTarget type only has a few methods.

In your case, you know exactly what kind of element will be in the target. So in order to tell the compiler that your target has the value property, you need to cast it into a more concrete type (`HTMLInputElement for example https://github.com/Microsoft/TypeScript/blob/master/src/lib/dom.generated.d.ts#L5248)

I don't think you can do that in a single shot (or at least I am not aware of a technique to do that), so you would need another 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])*/); 

An even cleaner way to do this (as we are repeating the map().map() twice, so we are not very DRY) we can use the compose operator given by xstream.

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])*/); 

Hope it helps :)

Upvotes: 1

Related Questions