czwartek, 29 listopada 2012

how about state machine in html widget?

I've got the task to create complicated widget to select date. When I crystallized in my minds how it must behave, then I saw many if/then conditions. When You are in a developing process it seems to be not so scary, but when You have to change it, or fix after few weeks, usually it is a bloody mess.

I stared wonder if there is a better way to handle this and here is a way (I think)  that could help. Use a state machine concept. We can create some instance variables to save state and relaying on them build all widget logic (it is crappy) like that:


The real state machine is something where you define available states, and events which changes the state. Pretty good lib to handle this is:
https://github.com/jakesgordon/javascript-state-machine . It allows You to define for one event many routes, depending on your actual state, which suits this state diagram. Also there are callback on enter/leave state and before/after fire event. To event you can pass message(an argument), so you can treat it as normal method, which do some extra stuff.


First of all is the pen and paper,  you need to draw simple graph for your control. Circles are the states and lines are the events, and that's all. When you properly design your graph, save this to code:

Define some callbacks on enter/leave state. Also useful are callbacks on fire specific event. To each callback will be passed arguments which allow You to do specific code basing on previous/next state, and argument passed explicitly to event. Now bind dom events and call events on state machine.


Further? OOP design of this example is probably not best. Operation explicitly on view should be in one class and flow in other.

Brak komentarzy:

Prześlij komentarz