Quite often you want to trigger global custom events for your application or website or what so ever. Well there are several pubsub (publish - subscribe) Libraries out there but luckily, if you use jQuery there is absolutley no need for an extra Library.
Click on the following button triggers a custom event (will pop up an alert!)
Well if you run through the jQuery docs you may have seen the
trigger()
thingy. You may also have seen that it is always bound to an Element but your target is to have it available globally.Nothing easier than this.
Just create a public jQuery Object and bind your custom Event triggers to this element. Following Example should help you.
#Watch out, this is COFFEESCRIPT
# Define the global Variable pubSub that is internally a empty jQuery Object
window.pubSub = $ {}
# Start the Script
$ ->
$('#myCustomButton').on "click", ->
# trigger our custom Event
pubSub.trigger "showMessage"
# Listen to the Custom Event and do stuff.
pubSub.on "showMessage", ->
alert('Yay... you triggered this')