msg-pubsub
v0.2.0
Published
msg-pubsub is a simple events dispatcher publish / subscribe library (just 0.9kb). aysnc, simple and usefull.
Downloads
1
Maintainers
Readme
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
.
import msg from 'msg-pubsub';
// or
var msg = require("msg-pubsub");
2. Simple usage
Use pub
method to publish message, use sub
method to subscribe message, unsub
to unsubscribe.
import msg from 'msg-pubsub';
function test_callback(data1, data2) {
console.log('this is msg 1');
}
// publish message
msg.pub('test_msg', 'test_data1', 'test_data2');
// subscribe message
var msgObj = msg.sub('test_msg', test_callback);
var msgObj2 = msg.sub('test_msg', function(data1, data2) {
console.log('this is msg 2');
});
// cancel message
msg.unsub(msgObj); // cancel message
msg.unsub('test_msg'); // cancel all messages called `test_msg`.
msg.unsub(test_callback); // cancel all `test_callback` methods.