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 onmessage(event) {
84 var obj = JSON.parse(event.data);
88 AFB_context.token = obj[3];
90 if (id && id in this.pendings) {
91 pend = this.pendings[id];
92 delete this.pendings[id];
96 var a = this.awaitens[id];
98 a.forEach(function(handler){handler(ans);});
100 pend && pend.onsuccess && pend.onsuccess(ans, this);
104 pend && pend.onerror && pend.onerror(ans, this);
113 function call(api, verb, request, onsuccess, onerror) {
114 var id = String(++this.counter);
115 this.pendings[id] = { onsuccess: onsuccess, onerror: onerror };
116 var arr = [CALL, id, api+"/"+verb, request ];
117 if (AFB_context.token) arr.push(AFB_context.token);
118 this.ws.send(JSON.stringify(arr));
121 function onevent(api, name, handler) {
122 var id = api+"/"+name;
123 var list = this.awaitens[id] || (this.awaitens[id] = []);
127 AFB_websocket.prototype = {
133 /*********************************************/
137 /*********************************************/
139 context: AFB_context,