Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //////////////// ---------> HTML
- <!DOCTYPE html>
- <html>
- <head>
- <script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/socket.io/1.3.6/socket.io.min.js"></script>
- <script src="{{ url_for('static', filename='index.js') }}"></script>
- <title>Vote</title>
- </head>
- <body>
- <ul id="votes">
- </ul>
- <hr>
- <!-- value of data-vote is using in javascript in button.dataset.vote-->
- <button data-vote="yes">Yes</button>
- <button data-vote="no">No</button>
- <button data-vote="maybe">Maybe</button>
- </body>
- </html>
- //////////////// ---------> Python:
- import os
- import requests
- from flask import Flask, jsonify, render_template, request
- from flask_socketio import SocketIO, emit
- app = Flask(__name__)
- app.config["SECRET_KEY"] = "SECRET_KEY"
- socketio = SocketIO(app)
- @app.route("/")
- def index():
- return render_template("index.html")
- # submit vote - this name is using in javascript in "socket.emit(...."
- @socketio.on("submit vote")
- def vote(data):
- selection = data["selection"]
- #
- emit("announce vote", {"selection": selection}, broadcast=True)
- if __name__ == '__main__':
- app.run(debug=True)
- //////////////// ---------> JAVASCRIPT
- document.addEventListener('DOMContentLoaded', () => {
- // Connect to websocket
- var socket = io.connect(location.protocol + '//' + document.domain + ':' + location.port);
- // When connected, configure buttons
- // socket.on(event, callback)
- // Parameter Type Description
- // event string The event name to define a callback for.
- // callback function The function to call when the event happens.
- socket.on('connect', () => {
- // Each button should emit a "submit vote" event
- document.querySelectorAll('button').forEach(button => {
- button.onclick = () => {
- // value from data-vote in html
- const selection = button.dataset.vote;
- socket.emit('submit vote', {'selection': selection});
- };
- });
- });
- // When a new vote is announced, add to the unordered list
- // announce vote - name from Python script
- socket.on('announce vote', data => {
- const li = document.createElement('li');
- li.innerHTML = `Vote recorded: ${data.selection}`;
- document.querySelector('#votes').append(li);
- });
- });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement