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 AFB_context = function(token, uuid) {
21 AFB_context.prototype = {
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 /*********************************************/
30 /**** AFB_websocket ****/
32 /*********************************************/
39 var PROTO1 = "x-afb-ws-json1";
41 AFB_websocket = function(onopen, onabort, ctx) {
42 this.ws = new WebSocket(urlws, [ PROTO1 ]);
45 this.ctx = ctx || new AFB_context();
46 this.ws.onopen = onopen.bind(this);
47 this.ws.onerror = onerror.bind(this);
48 this.ws.onclose = onclose.bind(this);
49 this.ws.onmessage = onmessage.bind(this);
51 this.onabort = onabort;
54 function onerror(event) {
61 this.onerror && this.onerror(this);
64 function onopen(event) {
71 function onclose(event) {
72 for (var id in this.pendings) {
73 var ferr = this.pendings[id].onerror;
74 ferr && ferr(null, this);
77 this.onclose && this.onclose();
80 function onmessage(event) {
81 var obj = JSON.parse(event.data);
85 this.ctx.token = obj[3];
87 if (id && id in this.pendings) {
88 pend = this.pendings[id];
89 delete this.pendings[id];
93 pend && pend.onsuccess && pend.onsuccess(ans, this);
97 pend && pend.onerror && pend.onerror(ans, this);
106 function call(api, verb, request, onsuccess, onerror) {
107 var id = String(++this.counter);
108 this.pendings[id] = { onsuccess: onsuccess, onerror: onerror };
109 var arr = [CALL, id, api+"/"+verb, request ];
110 if (this.ctx.token) arr.push(this.ctx.token);
111 this.ws.send(JSON.stringify(arr));
114 AFB_websocket.prototype = {
119 /*********************************************/
123 /*********************************************/
125 context: AFB_context,