Thursday, March 18, 2010

Events & Behaviors in Yii - Initial Notes

This one is a work in progress as I try to figure out how to use this aspect correctly. This are my "notes" from reading these documents.

I'm basing this on the following two document references:
http://www.yiiframework.com/doc/cookbook/44
http://www.yiiframework.com/doc/guide/basics.component (section on events)

Key Points

  • Events:

    • Event handlers are special properties that take methods as their values
    • Attaching a method to an event will cause the method to be invoked automatically where the event is raised
    • Event names are case-insensitive
    • Use "on" methods to define events for the component
    • ex: $this->onClicked = $callback
    • public function onClicked($event){ $this->raiseEvent('onClicked', $event); }
    • callback can be a global function or a class method, or an anonymous function. If a class method, pass as array($object,'methodName')
  • Behaviors

    • Behaviors are 'mixin's (interface with implemented methods -- included instead of inherited)
    • The Behavior class defines several functions or properties which then can be added to another class by attaching the behavior to the class

Questions:

  • Not sure what this means:

    "An event can be attached with multiple handlers."
    Does that mean that I can have multiple onClick assignments on the same object, or onClick assignments on multiple objects which will then all process the same event.
    Follow up: The Cookbook says you can attach multiple functions to the same object handle and they will be processed in the order in which they were added -- this will require testing ;)

Additional Referenced Reading