@@ -2,6 +2,7 @@ import { type BroadcastDriver } from "laravel-echo";
22import { onMounted , onUnmounted , ref , watch } from "vue" ;
33import { echo } from "../config" ;
44import type {
5+ BroadcastNotification ,
56 Channel ,
67 ChannelData ,
78 ChannelReturnType ,
@@ -178,6 +179,75 @@ export const useEcho = <
178179 } ;
179180} ;
180181
182+ export const useEchoNotification = <
183+ TPayload ,
184+ TDriver extends BroadcastDriver = BroadcastDriver ,
185+ > (
186+ channelName : string ,
187+ callback : ( payload : BroadcastNotification < TPayload > ) => void = ( ) => { } ,
188+ event : string | string [ ] = [ ] ,
189+ dependencies : any [ ] = [ ] ,
190+ ) => {
191+ const result = useEcho < BroadcastNotification < TPayload > , TDriver , "private" > (
192+ channelName ,
193+ [ ] ,
194+ callback ,
195+ dependencies ,
196+ "private" ,
197+ ) ;
198+
199+ const events = toArray ( event ) ;
200+ let listening = false ;
201+ let initialized = false ;
202+
203+ const cb = ( notification : BroadcastNotification < TPayload > ) => {
204+ if ( ! listening ) {
205+ return ;
206+ }
207+
208+ if ( events . length === 0 || events . includes ( notification . type ) ) {
209+ callback ( notification ) ;
210+ }
211+ } ;
212+
213+ const listen = ( ) => {
214+ if ( listening ) {
215+ return ;
216+ }
217+
218+ if ( ! initialized ) {
219+ result . channel ( ) . notification ( cb ) ;
220+ }
221+
222+ listening = true ;
223+ initialized = true ;
224+ } ;
225+
226+ const stopListening = ( ) => {
227+ if ( ! listening ) {
228+ return ;
229+ }
230+
231+ listening = false ;
232+ } ;
233+
234+ onMounted ( ( ) => {
235+ listen ( ) ;
236+ } ) ;
237+
238+ return {
239+ ...result ,
240+ /**
241+ * Stop listening for notification events
242+ */
243+ stopListening,
244+ /**
245+ * Listen for notification events
246+ */
247+ listen,
248+ } ;
249+ } ;
250+
181251export const useEchoPresence = <
182252 TPayload ,
183253 TDriver extends BroadcastDriver = BroadcastDriver ,
0 commit comments