This code is ugly and every function impure. For a language that espouses immutability and pure functions, there has to be a better way.
Flapjax - http://www.flapjax-lang.org/
Reactive extensions take the Observable pattern and extend it to support functional event stream transforms. Many examples can be seen here (http://rxwiki.wikidot.com/101samples)
I suggest we stick pretty close to the Rx solution. Due to the fact that ClojureScript is single threaded and will remain so for the foreseeable future (web workers communicate purely via message passing), it is possible to construct a much simplified version of Rx in ClojureScript.
I suggest the following interfaces:
Based on these interfaces, it is fairly easy to start composing blocks of code that call the methods on IObserver differently, and that actually emulate several of the functions found in clojure.core. I suggest the following stream functions:
map - applies a function to every event in a stream. If more than one stream is specified, the events of each stream are queued until a new value for each stream is available. Then all streams are processed one element at a time
reduce - reduces a stream by applying a function to each item and the accum value until onend is called. At this point the accum is pushed to the observers.
merge - simply interleaves the contents of each stream in the order that they are received
interleave - same as merge, but events are interleaved in a round-robin order.
throttle - same as map, but extra events are thrown way, not queued. Only the most recent of each event stream is processed
foreach - executes a function against every element in the stream. Assumes that side-effects take place.
Using the above, it's fairly simple to see how one could write our auto-complete in the following way:
Not only is this code concise, but it also presents the logic in a fairly functional manner.
After the above interfaces have been proven to work. The implementation of a DSL will be investigated (as a separate proposal). In this DSL we would expose to-observable as symbols where a observable/key pair are written as observable:key.
Topics for Discussion
Should a naming convention be adopted for event stream functions? Map is a good name for the map function, but I'd rather not confuse users.
Can we simplify this any more? Three interfaces aren't much, but those interfaces hide a lot of mutability. This mutability may be less of an issue in the single-threaded world of JS, but can we see any issues?
Some work by Stuart Sierra on Rx in Clojure: https://github.com/stuartsierra/cljque
Event programming in Clojure: https://github.com/ztellman/lamina/
TPL Dataflow, like Rx, but uses queues and processor blocks: http://msdn.microsoft.com/en-us/devlabs/gg585582.aspx