Php implements event listening. For more information about how to implement event listening, see jQuery's event binding logic. Main functions: 1. event binding supports binding multiple actions to an event and how to implement event listening at one time. refer to jQuery's event binding idea and briefly implement it.
Main functions:
1. event binding supports binding one event to multiple actions and one-time event binding.
2. trigger events
3. deregister the event
The code is as follows:
Class Event
{
Protected static $ listens = array ();
Public static function listen ($ event, $ callback, $ once = false ){
If (! Is_callable ($ callback) return false;
Self: $ listens [$ event] [] = array ('callback' => $ callback, 'one' => $ once );
Return true;
}
Public static function one ($ event, $ callback ){
Return self: listen ($ event, $ callback, true );
}
Public static function remove ($ event, $ index = null ){
If (is_null ($ index ))
Unset (self ::$ listens [$ event]);
Else
Unset (self: $ listens [$ event] [$ index]);
}
Public static function trigger (){
If (! Func_num_args () return;
$ Args = func_get_args ();
$ Event = array_shift ($ args );
If (! Isset (self ::$ listens [$ event]) return false;
Foreach (array) self: $ listens [$ event] as $ index => $ listen ){
$ Callback = $ listen ['callback'];
$ Listen ['one'] & self: remove ($ event, $ index );
Call_user_func_array ($ callback, $ args );
}
}
}
The following are some examples of calls:
The code is as follows:
// Adds a listener for a walk event.
Event: listen ('walk ', function (){
Echo "I am walking... n ";
});
// Adds a one-time event for listening to a walk.
Event: listen ('walk ', function (){
Echo "I am listening... n ";
}, True );
// Trigger the walk event
Event: trigger ('walk ');
/*
I am walking...
I am listening...
*/
Event: trigger ('walk ');
/*
I am walking...
*/
Event: one ('say', function ($ name = ''){
Echo "I am {$ name} n ";
});
Event: trigger ('say', 'demoka '); // output I am deeka
Event: trigger ('say', 'demo'); // not run
Class Foo
{
Public function bar (){
Echo "Foo: bar () is calledn ";
}
Public function test (){
Echo "Foo: foo () is called, agrs:". json_encode (func_get_args (). "n ";
}
}
$ Foo = new Foo;
Event: listen ('bar', array ($ foo, 'bar '));
Event: trigger ('bar ');
Event: listen ('test', array ($ foo, 'test '));
Event: trigger ('test', 1, 2, 3 );
Class Bar
{
Public static function foo (){
Echo "Bar: foo () is calledn ";
}
}
Event: listen ('bar1', array ('bar', 'Foo '));
Event: trigger ('bar1 ');
Event: listen ('bar2', 'Bar: Foo ');
Event: trigger ('bar2 ');
Function bar (){
Echo "bar () is calledn ";
}
Event: listen ('bar3', 'bar ');
Event: trigger ('bar3 ');
Bytes. Main functions: 1. event binding supports binding multiple actions to an event. one-time binding is supported...