gpt4 book ai didi

javascript - 如何从动态创建的输入中更新总和?

转载 作者:行者123 更新时间:2023-11-28 03:06:28 24 4
gpt4 key购买 nike

我有多个动态创建的输入(可以添加或删除输入)。以及显示输入总和的文本字段。如何动态附加可观察对象以及我的文本如何订阅所有这些对象?

因为我无法弄清楚如何创建可观察对象并将其附加到字段或如何使用它们的 id 访问它们。我没有太多代码要发布!有任何输入吗?

函数有循环并返回可观察值列表

    var source = Rx.Observable.fromEvent(cellVal, 'keyup',(evt) => evt.target.value).startWith(cellVal.value);
arr.push(source);
}
return arr;


values = funct() //calls function that returns array of obervables
var example = Rx.Observable.combineLatest(values);
example.subscribe(val => {
console.log('Sum:', val);
});

The inputs can be created or deleted and sum shud be updated accordingly

最佳答案

如果你想随着时间的推移向数组添加/删除可观察量,这意味着你需要一个状态(因为添加/删除)。如果你想坚持使用 rxjs,我知道的唯一无副作用的方法是使用 scan运算符(operator)。以下代码显示了一个实现:

界面

interface MappableObservable <T>{
key: number,
observable: Observable<T>
}

函数

// Function that adds to an array of MappableObservables
const addToState = (update: MappableObservable<string>) => (state: MappableObservable<string>[]): MappableObservable<string>[] =>
[...state, update];

// Function that deletes all items with given key from an array of MappableObservables
const deleteFromState = (key: number) => (state: MappableObservable<string>[]): MappableObservable<string>[] =>
state.filter(item => item.key !== key);

// Function that executes the above add or delete function inside a scan
const scanFn = (state: MappableObservable<string>[], fn: (state: MappableObservable<string>[]) => MappableObservable<string>[]) =>
fn(state)

执行

const DEFAULT_MAPPABLE_OBSERVABLE_STATE: MappableObservable<string>[] = [];
const add$: Subject<MappableObservable<string>> = new Subject();
const delete$: Subject<number> = new Subject();

const source$: Observable<string[]> = merge(
add$.pipe(map(addToState)),
delete$.pipe(map(deleteFromState))
).pipe(
scan(scanFn, DEFAULT_MAPPABLE_OBSERVABLE_STATE),
map(state => state.map(mappableObservable => mappableObservable.observable)),
switchMap(observables => combineLatest(observables))
)

添加或删除一些可观察到的源$

add$.next({key: 1, observable: of('uno')}) // Output: 'uno'
add$.next({key: 2, observable: of('duo')}) // Output: 'uno', 'duo'
add$.next({key: 3, observable: of('tri')}) // Output: 'uno', 'duo', 'tri'
add$.next({key: 2, observable: of('duo-duo')}) // Output: 'uno', 'duo', 'tri' 'duo-duo'
delete$.next(2); // Output: 'uno', 'tri'

仅供引用:仅当您重放它们或像我在本例中那样使用 of(...) 时,才可以直接观察到的结果。如果您有不可重播或即时的可观察对象,它们只会在它们全部新完成时发出

正在运行stackblitz

关于javascript - 如何从动态创建的输入中更新总和?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60567691/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com