2961: Escaped erb used embedded in javascript. Updated comments in
[arvados.git] / apps / workbench / app / assets / javascripts / event_log.js
1 /*
2  * This js establishes a websockets connection with the API Server.
3  */
4
5 /* Subscribe to websockets event log.  Do nothing if already connected. */
6 function subscribeToEventLog () {
7   // if websockets are not supported by browser, do not subscribe for events
8   websocketsSupported = ('WebSocket' in window);
9   if (websocketsSupported == false) {
10     return;
11   }
12
13   // check if websocket connection is already stored on the window
14   event_log_disp = $(window).data("arv-websocket");
15   if (event_log_disp == null) {
16     // need to create new websocket and event log dispatcher
17     websocket_url = $('meta[name=arv-websocket-url]').attr("content");
18     if (websocket_url == null)
19       return;
20
21     event_log_disp = new WebSocket(websocket_url);
22
23     event_log_disp.onopen = onEventLogDispatcherOpen;
24     event_log_disp.onmessage = onEventLogDispatcherMessage;
25
26     // store websocket in window to allow reuse when multiple divs subscribe for events
27     $(window).data("arv-websocket", event_log_disp);
28   }
29 }
30
31 /* Send subscribe message to the websockets server.  Without any filters
32    arguments, this subscribes to all events */
33 function onEventLogDispatcherOpen(event) {
34   this.send('{"method":"subscribe"}');
35 }
36
37 /* Trigger event for all applicable elements waiting for this event */
38 function onEventLogDispatcherMessage(event) {
39   parsedData = JSON.parse(event.data);
40   object_uuid = parsedData.object_uuid;
41
42   // if there are any listeners for this object uuid or "all", trigger the event
43   matches = ".arv-log-event-listener[data-object-uuid=\"" + object_uuid + "\"],.arv-log-event-listener[data-object-uuids~=\"" + object_uuid + "\"],.arv-log-event-listener[data-object-uuid=\"all\"],.arv-log-event-listener[data-object-kind=\"" + parsedData.object_kind + "\"]";
44   $(matches).trigger('arv-log-event', event.data);
45 }
46
47 /* Automatically connect if there are any elements on the page that want to
48    received event log events. */
49 $(document).on('ajax:complete ready', function() {
50   var a = $('.arv-log-event-listener');
51   if (a.length > 0) {
52     subscribeToEventLog();
53   }
54 });