一個類名的陣列和方法作為字串,例如, ['ClassName', 'methodName']
一個物件的陣列和一個方法作為字串,例如 [$obj, 'methodName']
第1步 - 要將處理程式係結到一個事件,應該呼叫 yii\base\Component::on() 方法
$obj = new Obj; // this handler is a global function $obj->on(Obj::EVENT_HELLO, 'function_name'); // this handler is an object method $obj->on(Obj::EVENT_HELLO, [$object, 'methodName']); // this handler is a static class method $obj->on(Obj::EVENT_HELLO, ['app\components\MyComponent', 'methodName']); // this handler is an anonymous function $obj->on(Obj::EVENT_HELLO, function ($event) { // event handling logic });
$obj->on(Obj::EVENT_HELLO, function ($event) { $event->handled = true; });
$obj->on(Obj::EVENT_HELLO, function ($event) { // ... }, $data, false);
namespace app\components; use yii\base\Component; use yii\base\Event; class Obj extends Component { const EVENT_HELLO = 'hello'; public function triggerEvent() { $this->trigger(self::EVENT_HELLO); } }
$obj = new Obj; // this handler is a global function $obj->off(Obj::EVENT_HELLO, 'function_name'); // this handler is an object method $obj->off(Obj::EVENT_HELLO, [$object, 'methodName']); // this handler is a static class method $obj->off(Obj::EVENT_HELLO, ['app\components\MyComponent', 'methodName']); // this handler is an anonymous function $obj->off(Obj::EVENT_HELLO, function ($event) { // event handling logic });