Вопрос

I am trying understand how to model events in ClojureScript. Designing an event queue in JavaScript is easy. You just keep a (mutable) array of functions, and provide helper functions to add or remove callbacks from the array. When you trigger the event, just go through all callbacks listed in the array and invoke them one after the other.

This paradigm is far from functional style - for instance there is no point in triggering the callbacks unless they have side effects. Moreover it is implemented using a mutable array. Still it seems to me that in ClojureScript one needs to be able to do event-driven programming to do anything useful. Now, I know that Google Closure already implements an event library, but my question is about implementing it natively.

Since all basic Clojure/ClojureScript data types are immutable, what would be an idiomatic way to implement this mechanism? Changing a ref? Resorting to mutable data structures from the host (Java resp JavaScript)?

If I understand correctly, agents are possibly the right tool in Clojure, but I see they are currently not implemented in ClojureScript.

Это было полезно?

Решение

Clojurescript One has a library, one.dispatch that is a good starting point. The wiki has usage examples here

Другие советы

As of 2013, the best way to achieve event handling in clojure is the excellent core.async library:

core.async enables event-driven programming with channels in a manner quite similar to the Go language.

Changing a ref/atom would be fine if you want to implement such solution as that is what most of the clojure libraries etc does when they have such situation where they need a store to store/remove stuff at runtime.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top