A simple publish subscribe library returning curried functions to work with cumin.
Belfry relies on cumin.js, as currently I use cumin for all my functional requirements.
- install cumin.js and belfry.js, The easiest way to do this is using bower
bower install cumin belfry
. - Include using script tags.
<script type="text/javascript" src="path/to/cumin.js"></script>
<script type="text/javascript" src="path/to/belfry.js"></script>
Belfry provides a singlton instance from the method getTower
.
var tower = Belfry.getTower();
Instance methods are publish
, subscribe
and unsubscribe
.
// create a function to subscribe to topics
var logger = function( data, topic ){
console.log( topic, data );
};
// subscribe to topic 'channel1'
// Keep returned id to unsubscribe
var subscriberId = tower.subscribe('channel1')(logger);
// publish to 'channel1'
// returns true if any listerns otherwise returns false
tower.publish('channel1')({message: 'Hello, World!'});
// Unsubscribe from topic
// requires both channel and subscriberId
tower.unsubscribe('channel1')(subscriberId);
Use curried function to create custom listeners
var ListenToResizeEvents = tower.subscribe('resize-events');
// Later
ListenToResizeEvents(logger);
Unsubscribe all listeners from a topic by not passing a subscriberId
ListenToResizeEvents(logger);
ListenToResizeEvents(otherFunc);
var clearResizeListeners = tower.unsubscribe('resize-events');
clearResizeListeners();
Useful code snippet to listen to all messages passing through a channel using cumin.
var logChannel = _.compose(_.invoke(_.log), tower.subscribe);
logChannel('thisChannel');
_.each(logChannel)('listen', 'to', 'all', 'these', 'channels');