Want to integrate websocket with emberjs? You have to implement a DS.Adapter that understands how to handle WebSockets. Here is an simple example:
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 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 | var SOCKET = 'ws://localhost:9090/some-websocket'; var ID = 'uuid'; var FIND = 'find'; var FIND_MANY = 'findMany'; var FIND_QUERY = 'findQuery'; var FIND_ALL = 'findAll'; /** * Implementation of WebSocket for DS.Store */ App.Store = DS.Store.extend({ revision: 4, adapter: DS.Adapter.create({ socket: undefined, requests: undefined, send: function(action, type, data, result) { /* Specific to your web socket server side implementation */ var request = { "uuid": generateUuid(), "action": action, "type": type.toString().substr(1), "data": data }; this.socket.send(JSON.stringify(request)); /* So I have access to the original request upon a response from the server */ this.get('requests')[request.uuid] = request; return request; }, find: function (store, type, id) { this.send(FIND, type, id); }, findMany: function (store, type, ids, query) { this.send(FIND_MANY, type, ids); }, findQuery: function (store, type, query, modelArray) { this.send(FIND_QUERY, type, query, modelArray).modelArray = modelArray; }, findAll: function (store, type) { this.send(FIND_ALL, type); }, /* Also implement: * createRecord & createRecords * updateRecord & updateRecords * deleteRecord & deleteRecords * commit & rollback */ init: function () { var context = this; this.set('requests', {}); var ws = new WebSocket(SOCKET); ws.onopen = function () { }; ws.onmessage = function(event) { var response = JSON.parse(event.data); var request = context.get('requests')[response.uuid]; switch (request.action) { case FIND: App.store.load(type, response.data[0]); break; case FIND_MANY: App.store.loadMany(type, response.data); break; case FIND_QUERY: request.modelArray.load(response.data); break; case FIND_ALL: App.store.loadMany(type, response.data); break; default: throw('Unknown Request: ' + request.action); } /* Cleanup */ context.get('requests')[response.uuid] = undefined; }; ws.onclose = function () { }; this.set('socket', ws); } }); }); |
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.