ThomasBurleson
12/3/2013 - 10:51 PM

Javascript Message Queue is a simple topic-based messaging (aka Pub/Sub) construct that also publishes customizable `addListener()`, `remove

Javascript Message Queue is a simple topic-based messaging (aka Pub/Sub) construct that also publishes customizable addListener(), removeListener(), and announceChange() APIs.

# ******************************************************************************************************
#
#  JMQ - jQuery-based Message Queue
#
#    This class provides a simple publish/subscribe mechanism
#    using the jQuery v1.7x Callbacks class as the notification engine
#    NOTE: here each instance of JMQ() has its `own` topic registry
#
#  Copyright (c) 2012 Mindspace
#
# ******************************************************************************************************
#

namespace 'mindspace.utils'

  JMQ:

    class JMQ

      constructor : ( @$log ) ->
        @$log.log( "mindspace.utils.JMQ::constructor() " )  

        buildQueue  = $?.Callbacks
        registry  = { }

        @topic    =  ( id ) =>
          dispatcher = id && registry[ id ] 
          
          if ( !dispatcher && id )
            queue = buildQueue()
            
            dispatcher =
              publish     : queue.fire
              subscribe   : queue.add
              unsubscribe : queue.remove
            
            registry[ id ] =  dispatcher
          
          return dispatcher

        return this#

  MessageQueue :

    #
    # MessageQueue (Pub/Sub) class extend to expose specific announce/add/remove methods
    #
    class MessageQueue extends JMQ

      # @param actions === 'Filter Node'
      constructor : ( actions, @$log ) ->
        super( @$log )

        @$log.log( "grimestone.utils.MessageQueue::constructor() " )

        angular.forEach(
          actions.split(' '),
          ((action) =>
            @["announce#{action}Change"] = @topic( action ).publish
            @["add#{action}Listener"]    = @topic( action ).subscribe
            @["remove#{action}Listener"] = @topic( action ).unsubscribe
            return
          ),this
        )
        return this