N
N
nonlux2017-05-13 08:55:47
JavaScript
nonlux, 2017-05-13 08:55:47

How to implement Rxjs toggle?

I'm getting into rxjs. Made a toggle decorator for the Dropdown component. Everything works, but I don't like the solution. Is there any way to avoid the "toggle/hide"
condition Rxjs, React.js, Recompose are used

//file toogleable.js
export const toggleable = Wrapped => componentFromStream((props$) => {
// toogleHandler  привязывается на onClick
  const { handler: toogleHandler, stream: toogle$ } = createEventHandler();
// вызов hideHandler  нижек
  const { handler: hideHandler, stream: hide$ } = createEventHandler();

  const show$ = Observable.merge(
    toogle$.mapTo('toogle'),
    hide$.mapTo('hide'))
          .startWith(false)
          .scan((state, type) => {
            if (type === 'toogle') {
              return !state;
            }
            if (type === 'hide') {
              return false;
            }

            return state;
          });


  return props$
    .combineLatest(
      show$,
      (props, show) => (
        <Wrapped
          {...props}
          show={show}
          onToggle={toogleHandler}
          onHide={hideHandler}
        />
      ));
});

class Foo extends Component {
    constructor(props) {
      super(props);
      this.refButton.bind(this);
      this.documentClick$ = Observable.fromEvent(global.document, 'click')
        .filter(event => this.button !== event.target)
        .do((event) => { this.props.onHide(event); });
    }

    componentDidMount() {
      this.documentClick$.subscribe();
    }
    componentWillUnmount() {
      this.documentClick$.unsubscribe();
    }
    refButton = (ref) => {
      this.button = ref;
    }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Manakov, 2017-05-13
@nonlux

Something like:

const show$ = Observable.merge(
    toogle$.map(() => state => !state),
    hide$.startWith({}).map(() => () => false)
)
          .scan((state, action) => action(state), false);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question