Issue
I'm trying to implement a solution that execute the following steps:
- Check if a condition is valid with a
filter
. - Check if
Ctrl
is pressed and execute some function if it is. - finally, execute another function.
I was able to make it work with that code:
const click = Observable.fromEvent(element, 'click');
click.filter(() => condition)
.do((event: MouseEvent) => {
if (!event.ctrlKey) {
// maybe do something...
}
}).subscribe(() => {
// aways do something else at end
});
I want to know if there is a more elegant solution that removes the if condition inside of do
method?
Solution
Not sure I understand the question, but here's a similar way of doing that and trying to keep the code as clean as possible :
const click$ = Observable.fromEvent(document, 'click');
// I don't know what's in your condition so I just return true
const condition = () => true;
const fnCtrlIsPressed = () => 'Ctrl is pressed';
const fnCtrlIsNotPressed = () => 'Ctrl is not pressed';
click$
.map(event => event.ctrlKey)
.map(isCtrlPressed => isCtrlPressed ?
fnCtrlIsPressed():
fnCtrlIsNotPressed())
.do(console.log)
.subscribe();
The output will be something like that :
Here's a working Plunkr : https://plnkr.co/edit/VwuXkk0QnVGC4hPCvtOo?p=preview
Answered By - maxime1992
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.