How to structure rxjs code

匆匆过客 提交于 2019-12-02 20:40:05

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 :)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!