Fix you
Event를 Bind하는 예제 본문
WebSocket을 Send하는 부분에서 이벤트를 bind하는 것처럼 쓰는 예제
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 | var WebsocketWrapper = function(url) { if (!window.WebSocket) { window.WebSocket = window.MozWebSocket; } let conn = new WebSocket(url); let callbacks = {}; this.bind = function(event_name, callback) { callbacks[event_name] = callbacks[event_name] || []; callbacks[event_name].push(callback); return this;// chainable }; this.remove = function(event_name) { delete callbacks[event_name]; }; this.send = function(event_name, event_data) { // *var payload = JSON.stringify({event:event_name, data: event_data}); conn.send( event_data ); // <= send JSON data to socket server return this; }; this.getSocket = function () { return conn; }; // dispatch to the right handlers conn.onmessage = function(evt) { //* var json = JSON.parse(evt.data) var ta = document.getElementById('responseText'); ta.value = ta.value + '\n' + evt.data //* dispatch(json.event, json.data) dispatch('res' + evt.data, evt.data) }; conn.onclose = function() { var ta = document.getElementById('responseText'); ta.value = ta.value + "\r\nWeb Socket closed"; dispatch('close',null) }; conn.onopen = function() { var ta = document.getElementById('responseText'); ta.value = "Web Socket opened!"; dispatch('open',null) }; let dispatch = function(event_name, message) { var chain = callbacks[event_name]; if (typeof chain == 'undefined') return; // no callbacks for this event for(var i = 0; i < chain.length; i++) { chain[i]( message ) } //* 1회성으로만 쓰기 위해서 delete callbacks[event_name]; } }; | cs |
호출하는 쪽
1 2 3 4 5 6 7 8 9 10 | function someSend(arg) { if (socket.getSocket().readyState != WebSocket.OPEN) { socket = new WebsocketWrapper(wsUrl); socket.bind('open', function() { sendProc(arg); }); } else { sendProc(arg); } } | cs |