4.4 Interceptando Eventos - Reference Documentation
Authors: Graeme Rocher, Peter Ledbrook, Marc Palmer, Jeff Brown, Luke Daley, Burt Beckwith
Version: null
4.4 Interceptando Eventos
Grails provides the ability to hook into scripting events. These are events triggered during execution of Grails target and plugin scripts.The mechanism is deliberately simple and loosely specified. The list of possible events is not fixed in any way, so it is possible to hook into events triggered by plugin scripts, for which there is no equivalent event in the core target scripts.
Grails proporciona la capacidad de interceptar eventos de scripts. Estos eventos son activados durante la ejecución de scripts de Grails y plugins.El mecanismo es deliberadamente simple y vagamente especificado. La lista de posibles eventos no es fija en modo alguno, por lo que es posible enlazar eventos activados por los scripts de plugin, para los que no hay evento equivalente en los scripts del núcleo.Defining event handlers
Event handlers are defined in scripts called_Events.groovy. Grails searches for these scripts in the following locations:
USER_HOME/.grails/scripts- user-specific event handlersPROJECT_HOME/scripts- applicaton-specific event handlersPLUGINS_HOME/*/scripts- plugin-specific event handlersGLOBAL_PLUGINS_HOME/*/scripts- event handlers provided by global plugins
Definición de manejadores de eventos
Los controladores de eventos se definen en un scripts llamado_Events.groovy. Grails busca estos scripts en las siguientes ubicaciones:
USER_HOME/.grails/scripts- manejadores de eventos específicos del usuario.PROJECT_HOME/scripts- manejadores de eventos específicos de la aplicación.PLUGINS_HOME / * / scripts- manejadores de eventos específicos de plugin.GLOBAL_PLUGINS_HOME / * / scripts- manejadores de eventos proporcionados por plugins globales.
Whenever an event is fired, all the registered handlers for that event are executed. Note that the registration of handlers is performed automatically by Grails, so you just need to declare them in the relevant
Cuando se desencadena un evento, se ejecutan todos los manejadores registrados para ese evento. Tenga en cuenta que el registro de controladores se realiza automáticamente por Grails, por lo que sólo es necesario declararlos en el archivo _Events.groovy file.Event handlers are blocks defined in _Events.groovy, with a name beginning with "event". The following example can be put in your /scripts directory to demonstrate the feature:eventCreatedArtefact = { type, name ->
println "Created $type $name"
}eventStatusUpdate = { msg ->
println msg
}eventStatusFinal = { msg ->
println msg
}_Events.groovy pertinente.Los manejadores de eventos son bloques definidos en _Events.groovy, con un nombre que empieza con "event". En el ejemplo siguiente se puede colocar en el directorio/scripts para demostrar esta característica:eventCreatedArtefact = { type, name ->
println "Created $type $name"
}eventStatusUpdate = { msg ->
println msg
}eventStatusFinal = { msg ->
println msg
}You can see here the three handlers
Aquí puede ver tres controladores eventCreatedArtefact, eventStatusUpdate, eventStatusFinal. Grails provides some standard events, which are documented in the command line reference guide. For example the compile command fires the following events:
CompileStart- Called when compilation starts, passing the kind of compile - source or testsCompileEnd- Called when compilation is finished, passing the kind of compile - source or tests
Triggering events
To trigger an event simply include the Init.groovy script and call the event() closure:eventCreatedArtefact, eventStatusUpdate, eventStatusFinal. Grails proporciona algunos eventos estándar, que se describen en la Guía de referencia de línea de comandos. Por ejemplo, el comando compile dispara los siguientes eventos:
CompileStart- llamado cuando se inicia la compilación, pasando el tipo de compilación - código fuente o pruebasCompileEnd- llamada una vez finalizada la compilación, pasando el tipo de compilación - código fuente o pruebas
Activación de eventos
Para desencadenar un evento simplemente debe incluir la secuencia de comandos Init.groovy y llamar a la closure event():includeTargets << grailsScript("_GrailsEvents")event("StatusFinal", ["Super duper plugin action complete!"])
Common Events
Below is a table of some of the common events that can be leveraged:includeTargets << grailsScript("_GrailsEvents")event("StatusFinal", ["Super duper plugin action complete!"])
Eventos habituales
A continuación es una tabla de algunos de los eventos habituales que se pueden utilizar:| Event | Parameters | Description |
|---|---|---|
| StatusUpdate | message | Passed a string indicating current script status/progress |
| StatusError | message | Passed a string indicating an error message from the current script |
| StatusFinal | message | Passed a string indicating the final script status message, i.e. when completing a target, even if the target does not exit the scripting environment |
| CreatedArtefact | artefactType,artefactName | Called when a create-xxxx script has completed and created an artefact |
| CreatedFile | fileName | Called whenever a project source filed is created, not including files constantly managed by Grails |
| Exiting | returnCode | Called when the scripting environment is about to exit cleanly |
| PluginInstalled | pluginName | Called after a plugin has been installed |
| CompileStart | kind | Called when compilation starts, passing the kind of compile - source or tests |
| CompileEnd | kind | Called when compilation is finished, passing the kind of compile - source or tests |
| DocStart | kind | Called when documentation generation is about to start - javadoc or groovydoc |
| DocEnd | kind | Called when documentation generation has ended - javadoc or groovydoc |
| SetClasspath | rootLoader | Called during classpath initialization so plugins can augment the classpath with rootLoader.addURL(...). Note that this augments the classpath after event scripts are loaded so you cannot use this to load a class that your event script needs to import, although you can do this if you load the class by name. |
| PackagingEnd | none | Called at the end of packaging (which is called prior to the Tomcat server being started and after web.xml is generated) |
| Evento | Parámetros | Descripción |
|---|---|---|
| StatusUpdate | mensaje | Pasa una cadena que indica el Estado y progreso de script actual. |
| StatusError | mensaje | Pasa una cadena que indica un mensaje de error en el script actual. |
| StatusFinal | mensaje | Pasa una cadena que indica el mensaje de estado final del script, es decir, al completar un target, incluso no cierra el entorno de script. |
| CreatedArtefact | artefactType, artefactName | Se llama cuando un script create-xxxx ha terminado y ha creado un artefacto |
| CreatedFile | nombre de archivo | Llamada siempre que se crea un fichero en el proyecto, sin incluir los archivos administrado por Grails. |
| Exiting | returnCode | Se llama cuando el entorno de script está a punto de cerrarse. |
| PluginInstalled | Nombre de Plugin | Se llama después de que se ha instalado un plugin. |
| CompileStart | tipo | Se llama cuando comienza la compilación, pasando el tipo de compilación - código fuente o pruebas |
| CompileEnd | tipo | Se llama cuando finaliza la compilación, pasando el tipo de compilación - código fuente o pruebas |
| DocStart | tipo | Se llama cuando la generación de documentación está a punto de empezar - javadoc o groovydoc |
| DocEnd | tipo | Se llama cuando se ha finalizado la generación de documentación - javadoc o groovydoc |
| SetClasspath | rootLoader | Llamado durante la inicialización del classpath para que los plugins pueda insertar entradas en el classpath con rootLoader.addURL(...). Dese cuenta de que esto inserta nuevas rutas después de que los scripts se cargen por lo que no se puede utilizar esto para cargar una clase su script de eventos necesita, aunque se puede hacer esto si carga la clase por su nombre. |
| PackagingEnd | ninguno | Llamado al final del empaquetamiento (que se llama antes de arrancar el servidor Tomcat y después de generar el web.xml) |

