msg-pubsub
English | 简体中文
msg-pubsub is a simple js lib (only
0.9kb
) for dispatching message by publish/subscribe pattern.
Can be used in:
- simple message/events dispatcher.
- Cross-component communication of React / Vue / Angular.
- message subscribe and publish.
API Methods
1. pub(msg_name, data1, data2, ...)
Async subscribe the message named msg_name
, and with datas
as the input of callback
function.
2. pubSync(msg_name, data1, data2, ...)
Sync subscribe the message named msg_name
, and with datas
as the input of callback
function, blocking.
3. sub(msg_name, callback, context)
Subscribe the msg_name
with callback
. callback
function will execute when the message named msg_name
published.
This function will return the msgObj
which can be used to cancel bind with the API un(msgObj)
.
4. subOnce(msg_name, callback, context)
Subscribe the msg_name
with callback
. It will be expired once Ttriggered.
Only can be triggered once, then it will be deleted automation.
5. unsub(msgObj / msg_name)
Cancel subscribe message. You can unsubscribe a message Object, or just unsubscribe a msg_name
, or unsubscribe the callback
function.
6. clear()
Clear all message/events.
Example
1. Import library
npm i msg-pubsub
You can import it with <script>
tag, or use keyword require
or import
.
; // or var msg = ;
2. Simple usage
Use pub
method to publish message, use sub
method to subscribe message, unsub
to unsubscribe.
; { console;} // publish messagemsg; // subscribe messagevar msgObj = msg;var msgObj2 = msg; // cancel messagemsg; // cancel messagemsg; // cancel all messages called `test_msg`.msg; // cancel all `test_callback` methods.