I'm having trouble writing event driven GUI code in a functional style, using Clojure and Seesaw. Specifically, I can't figure out how to pass the state of the program around without using globals, or some other unpleasant hack. My current approach is something like this:
(defn event-handler [gui-state event]
(update-gui! (get-new-state gui-state event)))
(defn update-gui! [gui-state]
(remove-all-listeners (gui-state :button))
(seesaw.core/listen (gui-state :button)
:action
(partial event-handler gui-state)))
It sets an event listener on the relevant component, with a partially applied function to advance the state and update the gui, including removing the old listener. Although this seems to be working, I don't really like it, partly because I can't pass the listener itself in the state (since it's not constructed until after I've already defined the state), so removing the old listener requires removing all listeners, which could cause problems as the program grows.
The closest solution I've found online is in this answer, but I don't know how to handle events as a stream like it shows. I'm sure there must be a better solution than my current approach, but I can't figure out what.
Can anyone show me how I can respond to user input events while still following a functional style?
The Streams from the linked answer seem like an analog of core.async channels.
Instead of removing all listeners each event maybe pass in a channel that has event details put to it. The same channel should go to the button's logic handler where it will repeatedly be taken from.
Related
I am looking for a pub/sub mechanism that behaves like a promise but can resolve multiple times, and behaves like an event except if you subscribe after a notification has happened it triggers with the most recent value.
I am aware of notify, but deferred.notify is order-sensitive, so in that way it behaves just like an event. eg:
d.notify('notify before'); // Not observed :(
d.promise.progress(function(data){ console.log(data) });
d.notify('notify after'); // Observed
setTimeout(function(){ d.notify('notify much later') }, 100); // Also Observed
fiddle: http://jsfiddle.net/foLhag3b/
The notification system I'd like is a good fit for a UI component that should update to reflect the state of the data behind it. In these cases, you don't want to care about whether the data has arrived yet or not, and you want updates when they come in.
Maybe this is similar to Immediate mode UIs, but is distinct because it is message based.
The state of the art for message based UI updating, as far as I'm aware, is something which uses a promise or callback to initialize, then also binds an update event:
myUIComponent.gotData(model.data);
model.onUpdate(myUIComponent.gotData); // doing two things is 2x teh workz :(
I don't want to have to do both. I don't think anyone should have to, the use case is common enough to abstract.
model.whenever(myUIComponent.gotData); // yay one intention === one line of code
I could build a mechanism to do what I want, but I wanted to see if a pub/sub mechanism like this already exists. A lot of smart people have done a lot in CS and I figure this concept must exist, I just am looking for the name of it.
To be clear, I'm not looking to change an entire framework, say to Angular or React. I'm looking only for a pub/sub mechanism. Preferably an implementation of a known concept with a snazzy name like notifr or lemme-kno or touch-base.
You'll want to have a look at (functional) reactive programming. The concept you are looking for is known as a Behavior or Signal in FRP. It models the change of a value over time, and can be inspected at any time (continuously holds a value, in contrast to a stream that discretely fires events).
var ui = state.map(render); // whenever state updates, so does ui with render() result
Some popular libraries in JS are Bacon and Rx, which use their own terminology however: you'll find properties and observables.
Suppose that I have a view-state targeted by many states. So many of them will have transitions with destination this state. For some of them, I want to display certain data on the page. So suppose if from state A->B then don't display, if C->B display.
I thought that if I knew the event that triggered the transition, I could easily do this... but I can't find a way (I am new to SWF).
Do you know how to do that? Or alternative ways to get the same result?
I've done something similar to this using a FlowExecutionListener. FlowExecutionListenerAdapter is provided as a base class for adding behavior on transition, state change, etc. An example of how to register such a listener can be found here in the docs. Each method is passed a Definition that contains meta data about the event. From that meta data you can determine if the event is one you're interested in and execute your custom logic.
Hope that helps.
When we call fsm.process_event('eventname');
is there a way to return true if the transition occured and false if "no_transition" was called or an exception occurred?
Thanks
Seeing as no one has answered so far I'll post my quite humble suggestion. You could try calling the current_state() method before and after calling fsm.process_event() and compare the results. This however would not cover the case of self transitions or internal transitions and is not something I would use if there are other alternatives (its a hack at best).
If you are trying to catch the case of an event not being handled by any state and just propagating through you could add one more bottom layer superstate which reports events that reach it (i.e. are ignored by all states they propagated through).
I have had situations where I needed to know if some event actually did something and when it did it (maybe it was deferred first and then executed). In that case I made my MSM post "ACK" messages to an outside queue, I'm not sure if this applies to your problem.
In my humble knowledge interrupts and state machines don't mix very well, I usually either simply swallow them or try and turn them into some event depending on the context. You should never allow you sates (the underlying function objects) to throw.
Note: I'm not talking about the names of event handlers. I'm talking about the names of the events themselves.
I tend to name events such that they describe what happened just before the event was raised. Adjectives tend to dominate this convention (CLICKED, SAVED, CHANGED, LOADED, etc).
Some competent peers have recently exposed me to the idea of naming events to describe what's about to happen (in response to the event). Verbs tend to dominate here (SAVE_DATA, GET_MEMBER, LOAD_RESULTS, SHOW_REPORT -- again, these are the names of events, not handlers or methods called from them).
I've decided the latter works well enough when you're in charge of both the event and the handler, and especially when there will only ever be one response you'll ever want to that event. Conversely, you can't very well name the event to match the verb (handler) that will follow if you don't have visibility to or control over it.
How do you name events, and why? Should one convention be enough (in a given shop, at the very least), or is it wiser to changed based on the size and scope of the code/project?
"Saving" for before event gets fired, and "Saved" after event happened.
Framework Design Guidelines suggest the following scheme:
Event Naming Guidelines
I name my events in the first way you described. This is because I want my handler to decide what to do with the event.
I think there are two things in interaction here:
Event - what has happened
Action - what you are going to do
Naming event by how you are going to react is a BAD IDEA. Name event by what has happened. Otherwise it will confuse people. If the reaction changes in the future and the name of event stays the same, it will perplex developers.
Example:
Event: Click(ed)
Action: LoadProducts
If you were to name the event "ToLoadProducts", then change your action to "DisplayFilterForm" and forget to update the event, it will look like:
Event: ToLoadProducts
Action: DisplayFilterForm
It's clear it looks strange and untidy, as though somebody dropped the work in the middle.
At work, we have a huge framework and use events to send data from one part of it to another. I recently started a personal project and I often think to use events to control the interactions of my objects.
For example, I have a Mixer class that play sound effects and I initially thought I should receive events to play a sound effect. Then I decided to only make my class static and call
Mixer.playSfx(SoundEffect)
in my classes. I have a ton of examples like this one where I initially think of an implementation with events and then change my mind, saying to myself it is too complex for nothing.
So when should I use events in a project? In which occasions events have a serious advantage over others techniques?
You generally use events to notify subscribers about some action or state change that occurred on the object. By using an event, you let different subscribers react differently, and by decoupling the subscriber (and its logic) from the event generator, the object becomes reusable.
In your Mixer example, I'd have events signal the start and end of playing of the sound effect. If I were to use this in a desktop application, I could use those events to enable/disable controls in the UI.
The difference between Calling a subroutine and raising events has to do with: Specification, Election, Cardinality and ultimately, which side, the initiator or the receiver has Control.
With Calls, the initiator elects to call the receiving routine, and the initiator specifies the receiver. And this leads to many-to-one cardinality, as many callers may elect to call the same subroutine.
With Events on the other hand, the initiator raises an event that will be received by those routines that have elected to receive that event. The receiver specifies what events it will receive from what initiators. This then leads to one-to-many cardinality as one event source can have many receivers.
So the decision as to Calls or Events, mostly has to do with whether the initiator determines the receiver is or the receiver determines the initiator.
Its a tradeoff between simplicity and re-usability. Lets take an metaphor of "Sending the email" process:
If you know the recipients and they are finite in number that you can always determine, its as simple as putting them in "To" list and hitting the send button. Its simple as thats what we use most of the time. This is calling the function directly.
However, in case of mailing list, you don't know in advance that how many users are going to subscribe to your email. In that case, you create a mailing list program where the users can subscribe to and the email goes automatically to all the subscribed users. This is event modeling.
Now, even though, in both above option, emails are sent to users, you are a better judge of when to send email directly and when to use the mailing list program. Apply the same judgement, hope that you would get your answer :)
Cheers,
Ajit.
I have been working with a huge code base at my previous work place and have seen, that using events can increase the complexity quite a lot and often unnecessarily.
I had often to reverse engineer existing code in order to fix it or to extend it.
In both cases, it is a lot easier to understand what is going on, when you can simply read a list of function calls instead of just seeing the raise of an event.
The event forces you to look for usages in order to fully understand what is happening. Not a problem with modern IDEs, but if you then encounter many functions, which also raise events, it quickly becomes complex. I had encountered cases, where it mattered in what order functions did subscribe to an event, even though most languages don't even gurantee a calling order...
There are cases when it is a really good idea to use events. But before you start eventing, consider the alternative. It is probably easier to read and mantain.
A Classic example for the use of events is a UI framework, which provides elements like buttons etc.
You want the function "ButtonPressed()" of the framework to call some of your functions, so that you can react to the user action.
The alternative to an event that you can subscribe to, would for example be a public bool "buttonPressed", which the UI framework exposes
and which you can regurlary check for beeing true or false. This is of course very ineffecient, when there are hundreds of UI elements.