RxJS form submission by Enter key and button click
Some time we have a form with just one input field and one button to submit. An example is like a chat form (stay tuned for more posts on this subject). Users type something on the form. It is expected that whether when users hit on the button or press the Enter/Return key, the form would be submitted.
Here is how to handle it with RxJS. By the way, I’ll show this in ReactJS and MaterializeCSS, 2 of favorite stacks. Don’t forget to launch the JS console to see the results.
First, we define a button clickStream and an enterKeyPressedStream from their corresponding events using Rx.Observable.fromEvent. Then using the operator Rx.Observable.merge, we merge these 2 streams into another stream called sendMessageStream.
We also have a stream of events when characters are typed in the input field. Let’s name this textEnteredStream. We will subscribe to this, capturing each character typed, until either an event from clickStream or enterKeyPressedStream happens. This is done using the takeUntil operator.
var mergedUntilStream = textEnteredStream.takeUntil(sendMessageStream);
Now it’s time to subscribe. In onNext, as I mentioned, we just capture the characters typed into a local variable called text. Do nothing in onError. In onComplete (that’s when the Enter key is pressed or button is clicked), we carry out the desired action. In this sample, it’s just writing out to the console. Then blank out the text field, keep the focus in it, and last but not least, we have to re-subscribe to the mergedUntilStream again.
var onComplete = () => {
console.log(‘submit ‘, text);
textField.value = ‘’;
textField.focus();
mergedUntilStream.subscribe(onNext, onError, onComplete);
}
That’s 40 lines of code, sparsely written.