RxJS Portfolio Example Documentation
// Get reference to search input and project elements
const searchInput = document.getElementById('search');
const projects = document.querySelectorAll('.project');
// Create an observable from the search input event
rxjs.fromEvent(searchInput, 'input').pipe(
rxjs.operators.map(event => event.target.value.toLowerCase()),
rxjs.operators.debounceTime(1000), // Wait for the user to stop typing for 300ms
rxjs.operators.distinctUntilChanged() // Only proceed if the input value has changed
).subscribe(searchTerm => {
// Filter projects based on search term
projects.forEach(project => {
const projectName = project.getAttribute('data-name').toLowerCase();
if (projectName.includes(searchTerm)) {
project.style.display = 'block';
} else {
project.style.display = 'none';
}
});
});
fromEvent
The fromEvent
function creates an observable that emits events of a specific type from a given target (like DOM elements).
In this example, fromEvent(searchInput, 'input')
creates an observable that emits events whenever the user types in the search input box.
pipe
The pipe
function allows you to compose multiple operators into a single chain of operations. It’s used to transform the observable in various ways.
In this example, pipe(...)
is used to chain multiple operators (map
, debounceTime
, distinctUntilChanged
) to the observable created by fromEvent
.
map
The map
function transforms the items emitted by an observable by applying a function to each item.
In this example, map(event => event.target.value.toLowerCase())
transforms each input event into the lowercase value of the text typed into the search box.
debounceTime
The debounceTime
function delays the emission of items from the observable by a specified time span. If a new item is emitted during that time span, the previous one is ignored.
In this example, debounceTime(300)
ensures that the observable only emits the value 300 milliseconds after the user stops typing, which helps prevent unnecessary filtering for every keystroke.
distinctUntilChanged
The distinctUntilChanged
function suppresses duplicate items emitted by the observable, meaning it only passes through an item if it is different from the last item emitted.
In this example, distinctUntilChanged()
ensures that the filtering logic only runs when the search term actually changes, avoiding redundant operations if the user types the same character repeatedly.
subscribe
The subscribe
function is how you “activate” the observable. When you subscribe, the observable starts emitting items, and you can define how to handle each emitted item.
In this example, .subscribe(searchTerm => { ... })
takes the search term (after all the transformations and filters) and applies the logic to show or hide projects based on the input.