Skip to content

Instantly share code, notes, and snippets.

@chiquitinxx
Created March 11, 2015 20:24
Show Gist options
  • Save chiquitinxx/ef2d33ce9d1a810ba216 to your computer and use it in GitHub Desktop.
Save chiquitinxx/ef2d33ce9d1a810ba216 to your computer and use it in GitHub Desktop.
Using RxJs from grooscript with @basescript
//Grooscript version of https://github.com/Reactive-Extensions/RxJS/tree/master/examples/autocomplete
import groovy.transform.BaseScript
import org.grooscript.asts.GsNative
import static org.grooscript.GrooScript.toJavascript
@BaseScript
ReactiveScript baseScript
def keyUp = observeEvent(textInput, 'keyup')
.map { it.target.value }
.filter { text -> text.size() > 2 }
.debounce(750)
.distinctUntilChanged()
def searcher = keyUp.flatMapLatest(searchWikipedia)
searcher.subscribe(
{ terms, resultsDom ->
resultsDom.empty()
terms[1].each { resultsDom.append "<li>$it</li>" }
}.rcurry(results), { errorMessage, resultsDom ->
resultsDom.empty()
resultsDom.append "<li>Error: $errorMessage</li>"
}.rcurry(results)
)
class ReactiveScript extends Script {
def selectors = [:]
@GsNative
def observeEvent(domElement, String eventName) {/*
return Rx.Observable.fromEvent(domElement, eventName)
*/}
def searchWikipedia = { term ->
$.ajax(url: 'http://en.wikipedia.org/w/api.php',
dataType: 'jsonp',
data: toJavascript([
action: 'opensearch',
format: 'json',
search: window.encodeURI(term)
])
).promise()
}
def propertyMissing(String name) {
if (!selectors[name]) {
selectors[name] = $("#$name")
}
selectors[name]
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment