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 /*********************************************/
11 var AFB_context = (function() {
13 var TOKEN = initialtoken;
15 var context = function(token, uuid) {
21 get token() {return TOKEN;},
22 set token(tok) {if(tok) TOKEN=tok;},
23 get uuid() {return UUID;},
24 set uuid(id) {if(id) UUID=id;}
29 /*********************************************/
31 /**** AFB_websocket ****/
33 /*********************************************/
34 var AFB_websocket = (function() {
40 var PROTO1 = "x-afb-ws-json1";
42 var result = function(onopen, onabort) {
44 if (AFB_context.token) {
45 u = u + '?x-afb-token=' + AFB_context.token;
47 u = u + '&x-afb-uuid=' + AFB_context.uuid;
49 this.ws = new WebSocket(u, [ PROTO1 ]);
53 this.ws.onopen = onopen.bind(this);
54 this.ws.onerror = onerror.bind(this);
55 this.ws.onclose = onclose.bind(this);
56 this.ws.onmessage = onmessage.bind(this);
58 this.onabort = onabort;
61 function onerror(event) {
68 this.onerror && this.onerror(this);
71 function onopen(event) {
78 function onclose(event) {
79 for (var id in this.pendings) {
80 var ferr = this.pendings[id].onerror;
81 ferr && ferr(null, this);
84 this.onclose && this.onclose();
87 function fire(awaitens, name, data) {
88 var a = awaitens[name];
90 a.forEach(function(handler){handler(data);});
91 var i = name.indexOf("/");
93 a = awaitens[name.substring(0,i)];
95 a.forEach(function(handler){handler(data);});
99 a.forEach(function(handler){handler(data);});
102 function reply(pendings, id, ans, offset) {
103 if (id in pendings) {
104 var p = pendings[id];
111 function onmessage(event) {
112 var obj = JSON.parse(event.data);
116 AFB_context.token = obj[3];
119 reply(this.pendings, id, ans, 0);
122 reply(this.pendings, id, ans, 1);
126 fire(this.awaitens, id, ans);
135 function call(method, request, onsuccess, onfailure) {
138 id = String(this.counter = 4095 & (this.counter + 1));
139 } while (id in this.pendings);
140 this.pendings[id] = [ onsuccess, onfailure ];
141 arr = [CALL, id, method, request ];
142 if (AFB_context.token) arr.push(AFB_context.token);
143 this.ws.send(JSON.stringify(arr));
146 function onevent(name, handler) {
148 var list = this.awaitens[id] || (this.awaitens[id] = []);
160 /*********************************************/
164 /*********************************************/
166 context: AFB_context,