· 7 years ago · Oct 04, 2018, 08:32 AM
1//////////////// ---------> HTML
2<!DOCTYPE html>
3<html>
4 <head>
5 <script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/socket.io/1.3.6/socket.io.min.js"></script>
6 <script src="{{ url_for('static', filename='index.js') }}"></script>
7 <title>Vote</title>
8 </head>
9 <body>
10 <ul id="votes">
11 </ul>
12 <hr>
13 <!-- value of data-vote is using in javascript in button.dataset.vote-->
14 <button data-vote="yes">Yes</button>
15 <button data-vote="no">No</button>
16 <button data-vote="maybe">Maybe</button>
17 </body>
18</html>
19
20//////////////// ---------> Python:
21import os
22import requests
23
24from flask import Flask, jsonify, render_template, request
25from flask_socketio import SocketIO, emit
26
27app = Flask(__name__)
28app.config["SECRET_KEY"] = "SECRET_KEY"
29socketio = SocketIO(app)
30
31@app.route("/")
32def index():
33 return render_template("index.html")
34
35# submit vote - this name is using in javascript in "socket.emit(...."
36@socketio.on("submit vote")
37
38def vote(data):
39 selection = data["selection"]
40 #
41 emit("announce vote", {"selection": selection}, broadcast=True)
42
43if __name__ == '__main__':
44 app.run(debug=True)
45
46//////////////// ---------> JAVASCRIPT
47document.addEventListener('DOMContentLoaded', () => {
48
49 // Connect to websocket
50 var socket = io.connect(location.protocol + '//' + document.domain + ':' + location.port);
51
52 // When connected, configure buttons
53 // socket.on(event, callback)
54 // Parameter Type Description
55 // event string The event name to define a callback for.
56 // callback function The function to call when the event happens.
57 socket.on('connect', () => {
58
59 // Each button should emit a "submit vote" event
60 document.querySelectorAll('button').forEach(button => {
61 button.onclick = () => {
62 // value from data-vote in html
63 const selection = button.dataset.vote;
64 socket.emit('submit vote', {'selection': selection});
65 };
66 });
67 });
68
69 // When a new vote is announced, add to the unordered list
70 // announce vote - name from Python script
71 socket.on('announce vote', data => {
72 const li = document.createElement('li');
73 li.innerHTML = `Vote recorded: ${data.selection}`;
74 document.querySelector('#votes').append(li);
75 });
76});