Skip to content

Instantly share code, notes, and snippets.

@duncan60
Last active March 30, 2017 09:47
Show Gist options
  • Save duncan60/5e11ba1770b33c1d0ad397abe7efa546 to your computer and use it in GitHub Desktop.
Save duncan60/5e11ba1770b33c1d0ad397abe7efa546 to your computer and use it in GitHub Desktop.
rx.js practice
const url = 'https://zh.wikipedia.org/w/api.php?action=opensearch&format=json&limit=5&origin=*';
const getSuggestList = (keyword) => fetch(url + '&search=' + keyword, { method: 'GET', mode: 'cors' })
.then(res => res.json())
const searchInput = document.getElementById('search');
const suggestList = document.getElementById('suggest-list');
const keyword = Rx.Observable.fromEvent(searchInput, 'input');
const selectItem = Rx.Observable.fromEvent(suggestList, 'click');
const render = (suggestAry = []) => {
suggestList.innerHTML = suggestAry
.map(item => `<li>${item}</li>`)
.join('');
}
selectItem
.filter(e => e.target.matches('li'))
.map(e => e.target.innerText)
.subscribe(text => {
searchInput.value = text;
render();
})
keyword
.filter(e => e.target.value.length > 2)
.debounceTime(100)
.switchMap(
e => getSuggestList(e.target.value),
(e, res) => res[1]
)
.subscribe(list => render(list))
//jsbin url:https://jsbin.com/wohewibafa/3/edit?js,output
const postList = [
'https://jsonplaceholder.typicode.com/posts/1',
'https://jsonplaceholder.typicode.com/posts/2',
'https://jsonplaceholder.typicode.com/posts/3'
]
const getPostData = (url) => {
return fetch(url)
.then(res => res.json());
//.catch((err) => err);
//如有這邊有捕抓catch 即使fetch錯誤subscribe不會跑道error
}
const rxFetch = (fetchs, fetchMethod) => {
return Rx.Observable.from(fetchs)
.concatMap(e => fetchMethod(e))
.bufferCount(fetchs.length)
.scan((origin, next) => {
return [ ...origin, next ];
}, []);
};
rxFetch(postList, getPostData).subscribe({
next: (value) => {
value.forEach((item) => console.table(item));
},
error: (err) => { console.log('rxFetch Error: ' + err); },
complete: (value) => { console.log('fetch complete'); }
});
//jsbin url: https://jsbin.com/gosaja/edit?js,output
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment