1 AFB = function(base, initialtoken){
3 var urlws = "ws://"+window.location.host+"/"+base;
4 var urlhttp = "http://"+window.location.host+"/"+base;
6 /*********************************************/
8 /**** AFB_context ****/
10 /*********************************************/
14 var TOKEN = initialtoken;
16 var context = function(token, uuid) {
22 get token() {return TOKEN;},
23 set token(tok) {if(tok) TOKEN=tok;},
24 get uuid() {return UUID;},
25 set uuid(id) {if(id) UUID=id;}
28 AFB_context = new context();
30 /*********************************************/
32 /**** AFB_websocket ****/
34 /*********************************************/
42 var PROTO1 = "x-afb-ws-json1";
44 AFB_websocket = function(onopen, onabort) {
45 this.ws = new WebSocket(urlws, [ PROTO1 ]);
49 this.ws.onopen = onopen.bind(this);
50 this.ws.onerror = onerror.bind(this);
51 this.ws.onclose = onclose.bind(this);
52 this.ws.onmessage = onmessage.bind(this);
54 this.onabort = onabort;
57 function onerror(event) {
64 this.onerror && this.onerror(this);
67 function onopen(event) {
74 function onclose(event) {
75 for (var id in this.pendings) {
76 var ferr = this.pendings[id].onerror;
77 ferr && ferr(null, this);
80 this.onclose && this.onclose();
83 function fire(awaitens, name, data) {
84 var a = awaitens[name];
86 a.forEach(function(handler){handler(data);});
87 var i = name.indexOf("/");
89 a = awaitens[name.substring(0,i)];
91 a.forEach(function(handler){handler(data);});
95 a.forEach(function(handler){handler(data);});
98 function reply(pendings, id, ans, offset) {
100 var p = pendings[id];
107 function onmessage(event) {
108 var obj = JSON.parse(event.data);
112 AFB_context.token = obj[3];
115 reply(this.pendings, id, ans, 0);
118 reply(this.pendings, id, ans, 1);
122 fire(this.awaitens, id, ans);
131 function call(method, request) {
132 return new Promise((function(resolve, reject){
135 id = String(this.counter = 4095 & (this.counter + 1));
136 } while (id in this.pendings);
137 this.pendings[id] = [ resolve, reject ];
138 arr = [CALL, id, method, request ];
139 if (AFB_context.token) arr.push(AFB_context.token);
140 this.ws.send(JSON.stringify(arr));
144 function onevent(name, handler) {
146 var list = this.awaitens[id] || (this.awaitens[id] = []);
150 AFB_websocket.prototype = {
156 /*********************************************/
160 /*********************************************/
162 context: AFB_context,