Search code examples
reactive-programmingcyclejs

CycleJS - subscribing click events of a child component


I am new to CycleJS and I would like to subscribe 'click' events of a child component from its parent component; but, it's not working. I'm able to subscribe events inside the child component. Is it possible to subscribe events of a child component from its parent component? If it's possible, how can I do it? Here's the parent component:

import Rx from 'rx';
import Cycle from '@cycle/core';
import CycleDOM from '@cycle/dom';
import isolate from '@cycle/isolate';
import _ from 'underscore';
import Inboxmails from './../components/inboxmails';

const {div} = CycleDOM;    
const Main =  (sources) => {

        const inboxmails=Inboxmails({DOM: sources.DOM});

        sources.DOM.select('#inbox_1')
                .events('click')
                .do(event => event.preventDefault())
                .subscribe(event => {
                    console.log(event);
                });


        const vtree$ = Rx.Observable.of(
                    div('.wrapper', [
                            inboxmails.DOM
                        ]));

            return {
                DOM: vtree$
            };
        };



    export default (sources) => isolate(Main)(sources);

And this is the child component

import Rx from 'rx';
import Cycle from '@cycle/core';
import CycleDOM from '@cycle/dom';
import isolate from '@cycle/isolate';
const { div} = CycleDOM;

const Inboxmails = function (sources) {
    const inboxmails$ = Rx.Observable.of(div([
        div("#inbox_1",[
            "Click here"
        ])])
    );
    return {
        DOM: inboxmails$    
    };
};

export default (sources) => isolate(Inboxmails)(sources);

Solution

  • Have the child return a sink of events that the parent needs.

    const Inboxmails = function (sources) {
        const inboxmails$ = Rx.Observable.of(div([
            div("#inbox_1",[
                "Click here"
            ])])
        );
        return {
            DOM: inboxmails$,
            clicks: sources.DOM.select('#inbox_1').events('click')  
        };
    };
    

    Then the parent can use inboxmails.clicks.

    However, in Cycle.js there should never be any subscribe in your code (unless it's for debugging). Subscribe calls should only be in drivers.