Created
August 14, 2016 03:46
-
-
Save yuizho/3d2fc99dec8b5ffa3a6bb8f3e58d10f8 to your computer and use it in GitHub Desktop.
reactive.html
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<html> | |
<head> | |
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/4.1.0/rx.lite.js"></script> | |
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> | |
<script> | |
$(function(){ | |
var inputStream = Rx.Observable.fromEvent($('#query'), 'keyup') | |
.pluck('target', 'value') | |
.throttle(300) | |
.filter(function(text) {return text.length > 0;}) | |
.distinctUntilChanged() | |
.map(function(text) { | |
var url = 'https://api.github.com/search/repositories?q=' + text; | |
return url; | |
}) | |
var executingStream = new Rx.Subject(); | |
var repositoriesStrem = inputStream | |
.flatMap(function(query) { | |
executingStream.onNext(true); | |
return Rx.Observable.fromPromise($.ajax({url: query})) | |
.finally(function() {executingStream.onNext(false)}); | |
}) | |
.map(function(res) { | |
return res.items; | |
}); | |
executingStream.subscribe(function(executing) { | |
if (executing) { | |
$('#result').html(""); | |
$('#result').append('loading...'); | |
} | |
}); | |
repositoriesStrem.subscribe(function(repos) { | |
$('#result').html(""); | |
$('#list').html(""); | |
for(var i = 0, len = repos.length; i < len; i++) { | |
$('#list').append('<li>' + repos[i].name + '</li>'); | |
} | |
}) | |
}); | |
</script> | |
</head> | |
<body> | |
<input type="text" id="query" /> | |
<div id="result"></div> | |
<ul id="list"></ul> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment