Comment on page
Events
A simple way for UI components to communicate with each other.
Events and listeners provide an elegant means for your components to communicate with each other. You can emit events from one component, listen for them on another component, and then execute code and re-render the listener.
You can fire events from:
- Actions using emit(), emitUp(), emitSelf(), and emitTo()
- Templates using $emit()
<!--- Action --->
<cfscript>
function addPost() {
emit( "postAdded" );
}
</cfscript>
<!--- Templates --->
<cfoutput>
<div>
<button wire:click="$emit( 'postAdded' )">Add Post</button>
</div>
</cfoutput>
<!--- Javascript --->
<script>
cbwire.emit( 'postAdded' );
</script>
You can send parameters as your emitting an event.
function addPost() {
var post = getInstance( "PostService" ).create( data );
emit( "postAdded", post.getId() );
}
<button wire:click="$emit( 'postAdded', post.getId() )">Add Post</button>
<script>
cbwire.emit( 'postAdded', [ '#post.getID()#' ] );
</script>
When working with nested components, sometimes you may want to emit events only to parent components and no children or sibling components.
For this, you can use the emitUp() method.
<cfoutput>
<div>...</div>
</cfoutput>
<cfscript>
function addPost() {
emitUp( "postAdded" );
}
</cfscript>
<button wire:click="$emitUp( 'postAdded' )">Add Post</button>
You can emit events to components of a specific type ( name ) using emitTo().
<cfoutput>
<div>...</div>
</cfoutput>
<cfscript>
function addPost() {
emitTo( "topBar", "postAdded" );
}
</cfscript>
<button wire:click="$emitTo( 'topBar', 'postAdded' )">Add Post</button>
You can emit events to the component that fired the event using emitSelf().
<cfoutput>
<div>...</div>
</cfoutput>
<cfscript>
function addPost() {
emitSelf( "postAdded" );
}
</cfscript>
<button wire:click="$emitSelf( 'postAdded' )">Add Post</button>
You register event listeners using the listeners struct of your component.
Listeners are a key/value pair where the key is the event to listen for, and the value is the method to invoke on the component.
<cfscript>
listeners = {
"postAdded": "incrementPostCount"
};
function incrementPostCount() {
// Increment the post count
}
</cfscript>
JavaScript keys are case-sensitive. You can preserve the key casing in CFML by surrounding your listener names in quotations.
Last modified 2mo ago