【发布时间】:2016-06-18 11:43:37
【问题描述】:
我在组合 observables 方面有一点(或大)问题。我正在实现某种标签输入。
this._allTags 都是可用的标签。
我有 4 个流:
this._suggestions = new this.rx.Subject;
this._searchText = new this.rx.Subject;
this._selectedIndex = new this.rx.Subject;
this._eventsStream = new this.rx.Subject;
搜索方式:
search(searchText) {
this._searchText.onNext(searchText);
this._selectedIndex.onNext(-1);
}
KeyDown 方法:
keyDown(event) {
this._eventsStream.onNext(event);
}
搜索逻辑:
const partitionSearchText = this._searchText
.partition((searchText) => !!searchText); //check if searchText is not empty
//put filtered array to this._suggestions stream
partitionSearchText[0]
.subscribe((searchText) => this._suggestions.onNext(
this._allTags.filter((item) => ~item.name.toLowerCase().indexOf(searchText.toLowerCase()))
));
//put empty array to this._suggestions stream if there is no searchText
partitionSearchText[1]
.subscribe((searchText) => this._suggestions.onNext([]));
我想实现事件。如果存在 searchText 和 keyDown 事件,那么我想增加 this._selectedIndex,但如果 this._selectedIndex 将与 this._suggestions 长度相同,则不要增加它。
这是我目前实现的:
const eventsWithSearchText = this._searchText
.map((searchText) => !!searchText ? this._eventsStream : this.rx.Observable.empty())
.switch()
const keyDownEvents = eventsWithSearchText
.filter((event) => event.keyCode === DOWN_KEY)
keyDownEvents
.subscribe((event) => event.preventDefault())
const isNotLast = this._selectedIndex
.combineLatest(this._suggestions, (index, sugg) => index !== sugg.length - 1);
keyDownEvents
.subscribe((item) => {
this._selectedIndexValue++
this._selectedIndex.onNext(this._selectedIndexValue);
});
所以,它会增加this._selectedIndex,但当它与this._suggestions 长度相同时不会停止。
你能帮忙吗?
【问题讨论】:
-
请准备一把小提琴。
标签: javascript angularjs ecmascript-6 rxjs observable