How to structure rxjs code

前端 未结 1 1364
别那么骄傲
别那么骄傲 2021-02-02 13:35

How does one structure an rxjs app? There are about a hundred toy intro examples, but not a single example of a full app, with widgets, subwidgets, etc., showing data flow throu

1条回答
  •  不思量自难忘°
    2021-02-02 14:04

    Pass the observables to the widget's constructor as arguments and let the widget subscribe or transform it with additional monads before passing it to its sub-widget constructors. The widget will manage its own subscriptions.

    If a widget produces data (e.g. user input), expose it as Observable properties on the widget.

    Note the widgets themselves are not part of the observable stream. They just consume input streams and produce output streams.

    // main app
    var someState = Rx.Observable....;
    var someWidget = createSomeWidget(someState, ...);
    var s = someWidget.userData.map(...).subscribe(...);
    
    // SomeWidget
    var SomeWidget = function ($element, state, ...) {
        this.userData = $element
            .find("button.save")
            .onAsObservable("click")
            .map(...collect form fields...);
    
        // we need to do stuff with state
        this.s = state.subscribe(...);
    
        // we also need to make a child widget that needs some of the state
        // after we have sanitized it a bit.
        var childState = state.filter(...).map(...)...;
        this.childWidget = new ChildWidget(childState, ...);
    
        // listen to child widgets?
    }
    

    And so on. If you are using Knockout, you can take advantage of ko.observable to create two-way observable streams and sometimes avoid needing to add output properties on your widgets, but that is a whole nother topic :)

    0 讨论(0)
提交回复
热议问题