socket.io扩展原始客户端js库

时间:2015-07-27 04:58:15

标签: javascript node.js socket.io

这是我原来的客户代码

var socket = io.connect('http://localhost:7048');

socket.on('channel', function (mess) {

    console.log(mess);

});

socket.on('message', function (mess) {

    console.log(mess);

});

如何扩展原始库以便获得类似的内容。此类代码由 pubnub 使用。

var myPlugin = MYPLUGIN({
    host: 'http://localhost:7048'
});

myPlugin.listen({
    channel: 'channel',
    message: function(m){console.log(m)},
    error: function(m){console.log(m)}
});

myPlugin.listen({
    channel: 'message',
    message: function(m){console.log(m)},
    error: function(m){console.log(m)}
});

myPlugin.unlisten({
    channel : 'message',
});

1 个答案:

答案 0 :(得分:0)

如果你试图让它像pubnub上的代码那样只是因为pubnub使用了这种语法并且你已经习惯了它,我不建议这么做,但如果你有一个API,你需要有一个特定的架构然后才行。

我建议构建一个包装器。

function MyPlugin(hostObj) {

    function listen(listenObj) {
        //your code here
    }

    function unlisten(unlistenObj) {
        //your code here
    }

    //this makes your functions public
    Object.defineProperties(this, {
        "listen": {value: listen},
        "unlisten": {value: unlisten}
    });

    return this;
}