|
1 | 1 | $(function() { |
2 | | - var $askButton = $('#ask-btn'); |
| 2 | + /* Set up realtime library and authenticate using token issued from server */ |
| 3 | + var ably = new Ably.Realtime({ authUrl: '/auth' }); |
| 4 | + var answersChannel = ably.channels.get('wolfram:answers'); |
| 5 | + var questionsChannel = ably.channels.get('wolfram:questions'); |
| 6 | + |
| 7 | + var $answers = $('#answers'), |
| 8 | + $status = $('#status'), |
| 9 | + $askButton = $('#ask-btn'), |
| 10 | + $question = $('#question'); |
| 11 | + |
| 12 | + /* Subscribe to answers published on this channel */ |
| 13 | + answersChannel.subscribe(function(message) { |
| 14 | + var $question = $('<div class="question">').text(message.data.question); |
| 15 | + var $answer = $('<div class="answer">').text(message.data.answer); |
| 16 | + var $stat = $('<div class="stat">').text("Wolfram took " + message.data.wolframTime + "ms"); |
| 17 | + $answers.prepend($('<div>').append($stat).append($question).append($answer)); |
| 18 | + }); |
| 19 | + |
3 | 20 | $askButton.on('click', function() { |
4 | | - alert("Not yet implemented"); |
| 21 | + var question = $question.val(); |
| 22 | + if (question.replace(' ') != '') { |
| 23 | + /* Publish question to the Ably channel so that the queue worker receives it via queues */ |
| 24 | + questionsChannel.publish('question', question, function(err) { |
| 25 | + if (err) { |
| 26 | + showStatus('Failed to publish question!'); |
| 27 | + $question.val(question); |
| 28 | + return; |
| 29 | + } |
| 30 | + clearStatus(); |
| 31 | + }); |
| 32 | + showStatus('Sending question...'); |
| 33 | + $question.val(''); |
| 34 | + } |
5 | 35 | }); |
| 36 | + |
| 37 | + ably.connection.on('connecting', function() { showStatus('Connecting to Ably...'); }); |
| 38 | + ably.connection.on('connected', function() { clearStatus(); }); |
| 39 | + ably.connection.on('disconnected', function() { showStatus('Disconnected from Ably...'); }); |
| 40 | + ably.connection.on('suspended', function() { showStatus('Disconnected from Ably for a while...'); }); |
| 41 | + |
| 42 | + function showStatus(text) { |
| 43 | + $status.text(text).show(); |
| 44 | + } |
| 45 | + |
| 46 | + function clearStatus() { |
| 47 | + $status.fadeOut(750); |
| 48 | + } |
6 | 49 | }); |
0 commit comments