About the Handler in gen_event

Vance Shipley vances@REDACTED
Tue Feb 25 19:52:02 CET 2003


Suresh,

The State is any term which you will find usefull to perform the task
at hand.  Since there are no global variables in Erlang you must pass
all the data needed with each function call.  This is the purpose of 
State.  Make state a record and keep stuff in there that you need to
keep track of:

-record(state, {foo_counter = 0, been_there = false}).

init(_) ->
	{ok, #state{}}.

handle_event(foo, State) ->
	% keep track of how many of these events have been received
	NewState = State#state{foo_counter + 1},
	...
	{ok, NewState};
handle_event(there, State) when State#state.been_there ->
	{ok, State};
handle_event(there, State) ->
	NewState = State#state{been_there = true},
	 % do something only the first time this event is received
	... 
	{ok, NewState};
handle_event(Event, State) ->
	{ok, State}.


In this way you can have persistent data.  State doesn't have to be a
record, it could be a tuple or any term.  If you need only the 
"been_there" knowledge you could have State just be an atom:

init(_) ->
        {ok, false}.

handle_event(there, State) when State ->
	{ok, State};
handle_event(there, State) ->
	 % do something only the first time this event is received
	...
	{ok, true};


The point being that State is yours to do with what you want. 


	-Vance



}  I did not get the concept of the 'State' exactly  incase of  all the
}  callback functions, 
}  
}  Any tips can help me more in working and debugging with callback modules  
}  
}  
}  regards 
}  
}  
}  suresh s   



More information about the erlang-questions mailing list