我在节点js上使用pubnub。我注意到在我的套接字代码中我经常需要pubnub.js并在每次发送消息时传递pubsub密钥(在我的发布函数中)。我已经更新了代码,以便在我的模块中创建一个pubnub实例。但是,我想知道这是否是防弹和正确的方法。
(function(root, factory) {
/* CommonJS */
if (typeof exports == 'object') module.exports = factory()
/* AMD module */
else if (typeof define == 'function' && define.amd) define(factory)
/* Browser global */
else root.Socket = factory();
}
(this, function() {
//
//
// Is it ok to strike up a once only instance of pubnub here
// in Node, or should i being doing it every time i call my publish
// function? The below should be the right way to do it> Require
// pubnub when the node instance starts, get an instance and use it
// forever more.
//
//
var Pubnub = require("./pubnub"),
pubnub = Pubnub({
publish_key: "pub-c-xx",
subscribe_key: "sub-c-xxx"
});
function publish(channel, data, cb){
//
//
// We use the instance above, BUT is this OK.
//
pubnub.publish({
channel : channel,
message : data,
callback : function(ev){
if (cb) return cb(ev);
}
});
}
var exports = {
publish: publish,
};
return exports;
}));