1 // ==========================================================================
  2 // Project:   SC.WebSocket
  3 // Copyright: ©2013 Nicolas BADIA and contributors
  4 // License:   Licensed under MIT license (see license.js)
  5 // ==========================================================================
  6 
  7 /** 
  8   @namespace
  9   
 10   A WebSocket Delegate is consulted by `SC.WebSocket` when events are received.
 11   You may want to handle this events before propagate them to eventual listeners.
 12 
 13   Example:
 14 
 15     var ws = SC.WebSocket.create({
 16       server: 'ws://server',
 17       delegate: MyApp.WebSocketDelegate
 18     });
 19   
 20   @since SproutCore 1.11
 21   @author Nicolas BADIA
 22 */
 23 SC.WebSocketDelegate = {
 24   
 25   /**
 26     Walk like a duck
 27 
 28     @type Boolean
 29   */
 30   isWebSocketDelegate: true,
 31 
 32   // ..........................................................
 33   // CALLBACKS
 34   //
 35 
 36   /**
 37     The passed webSocket connection is open.
 38 
 39     @param webSocket {SC.WebSocket} The webSocket object
 40     @param event {Event}
 41   */
 42   webSocketDidOpen: function (webSocket, event) {},
 43 
 44   /**
 45     A message has been received. Before processing it, you have
 46     a chance to check it. 
 47 
 48     For example, if `isJSON` is true, you will want to check if the message
 49     is a correct JSON.
 50 
 51     @param webSocket {SC.WebSocket} The webSocket object
 52     @param data {String}  
 53     @returns {String|Boolean} Return true to prevent further handling
 54   */
 55   webSocketDidReceiveMessage: function (webSocket, data) {
 56     switch(data) {
 57       case 'ping': return true; break;
 58     }
 59 
 60     if (this.get('isJSON')) {
 61       try {
 62         JSON.parse(data);
 63       }
 64       catch(e) {
 65         return true;
 66       }
 67     }
 68   },
 69 
 70   /**
 71     The websocket connection is close. Return true to prevent a
 72     reconnection or further handling.
 73 
 74     @param webSocket {SC.WebSocket} The webSocket object
 75     @param closeEvent {CloseEvent} The closeEvent
 76     @returns {Boolean} Return true to prevent further handling
 77   */
 78   webSocketDidClose: function (webSocket, closeEvent) {},
 79 
 80   /**
 81     Call when an error occur.
 82 
 83     @param webSocket {SC.WebSocket} The webSocket object
 84     @param event {Event} 
 85     @returns {Boolean} Return true to prevent further handling
 86   */
 87   webSocketDidError: function (webSocket, event) {},
 88 
 89 };
 90 
 91