* @since 2.0 */ class Behavior extends \yii\base\Object { /** * @var Component the owner of this behavior */ public $owner; /** * Declares event handlers for the [[owner]]'s events. * * Child classes may override this method to declare what PHP callbacks should * be attached to the events of the [[owner]] component. * * The callbacks will be attached to the [[owner]]'s events when the behavior is * attached to the owner; and they will be detached from the events when * the behavior is detached from the component. * * The callbacks can be any of the followings: * * - method in this behavior: `'handleClick'`, equivalent to `array($this, 'handleClick')` * - object method: `array($object, 'handleClick')` * - static method: `array('Page', 'handleClick')` * - anonymous function: `function($event) { ... }` * * The following is an example: * * ~~~ * array( * 'beforeValidate' => 'myBeforeValidate', * 'afterValidate' => 'myAfterValidate', * ) * ~~~ * * @return array events (array keys) and the corresponding event handler methods (array values). */ public function events() { return array(); } /** * Attaches the behavior object to the component. * The default implementation will set the [[owner]] property * and attach event handlers as declared in [[events]]. * Make sure you call the parent implementation if you override this method. * @param Component $owner the component that this behavior is to be attached to. */ public function attach($owner) { $this->owner = $owner; foreach ($this->events() as $event => $handler) { $owner->on($event, is_string($handler) ? array($this, $handler) : $handler); } } /** * Detaches the behavior object from the component. * The default implementation will unset the [[owner]] property * and detach event handlers declared in [[events]]. * Make sure you call the parent implementation if you override this method. */ public function detach() { if ($this->owner) { foreach ($this->events() as $event => $handler) { $this->owner->off($event, is_string($handler) ? array($this, $handler) : $handler); } $this->owner = null; } } }