latte_web2
Version:
51 lines • 1.49 kB
JavaScript
(function(define) { 'use strict';
define("latte_web/rpc/socketRpc", ["require", "exports", "module", "window"],
function(require, exports, module, window) {
var latte_lib = require("latte_lib");
function Rpc(methods) {
this.methods = methods || {};
this.id = 0;
};
(function() {
this.Set = function(method, fn) {
this.methods[method] = fn;
}
this.addSocket = function(socket) {
var self = this;
var backData = function(err, result, id) {
return {
error: err,
result: result,
id: id
};
};
socket.Call = function(handle, params, callback) {
socket.send(JSON.stringify({
method: handle,
params: params,
id: ++self.id
}));
callback && self.once(self.id, callback.bind(socket));
}
socket.on("message", function(data) {
data = JSON.parse(data);
if(data.method) {
var method = self.methods[data.method];
if(method) {
if(!latte_lib.isArray(data.params)) {
data.params = [].concat(data.params);
}
data.params.push(function(err, result) {
socket.send(JSON.stringify(backData(err, result, data.id)))
});
method.apply(socket, data.params);
}
}else if(data.id) {
socket.emit(data.id, data.error, data.result);
}
});
}
}).call(Rpc.prototype);
module.exports = Rpc;
});
})(typeof define === "function"? define: function(name, reqs, factory) { factory(require, exports, module); });