kist-pubsub
Simple publish/subscribe system.
Installation
npm install kist-pubsub --save bower install kist-pubsub --save
API
new PubSub(options)
Returns: PubSub
options
Type: Object
Instance options.
Property | Type | Description | Default value |
---|---|---|---|
event |
Boolean |
Should subscribed event have event object as first argument in passed callback (same as in standard jQuery event system). | true |
queue |
Boolean |
Should this instance implement queue system. When you subscribe to that specific event at later date, callback with data from last already applied callback for that specific event will be activated. | false |
namespace |
String |
Default event namespace for this instance of PubSub system. | '' |
.publish(event, data)
Publish data for specific event.
event
Type: String
Required
Event to publish.
data
Type: Array|Object
Required
Data to pass via published event. Behaves same as trigger
in standard jQuery event system.
In addition to behaving like jQuery trigger
, if you pass more than one argument (not counting event), all arguments will be passed as list of arguments to subscribe
methods.
.subscribe(event, callback, condition)
Subscribe to specific event.
event
Type: String
Required
Event to subscribe to.
callback
Type: Function
Required
Callback to run when event is published. Provided arguments are:
Argument | Type | Description |
---|---|---|
e |
$.Event |
Standard event object. Won’t be passed if event property inside initialization object is set to false . |
args… |
Mixed |
List of arguments after that is data passed via published event. |
condition
Type: Function
If return value is truthy value, it will activate callback
function. Gets same arguments like callback
.
.subscribeOnce(event, callback, condition)
Subscribe to specific event only once.
API is same as for subscribe.
.unsubscribe(event)
Unsubscribes from specific event.
event
Type: String
Required
Event to unsubscribe from.
.destroy()
Destroy/unsubscribe from all events.
Examples
Initialization.
var PubSub = ;var pubsub = event: true queue: false namespace: 'appNs';
Trigger event with specific data.
pubsub;pubsub;pubsub;pubsub;
Subscribe to event foo.bar
.
pubsub;pubsub;
Subscribe only once to event foo.bar
.
pubsub;pubsub;
Unsubscribe from event foo.bar
.
pubsub;
Destroy/unsubscribe from all events.
pubsub;
AMD and global
; window$kistPubSub;
Browser support
Tested in IE8+ and all modern browsers.
Acknowledgments
Plugin is based on jQuery tiny pub/sub but implements some options available either in previous versions or from community contributions.
License
MIT © Ivan Nikolić