diff --git a/index.html b/index.html index 964bf62..fe77d4a 100644 --- a/index.html +++ b/index.html @@ -16,9 +16,9 @@ // const init = JSON.stringify({event: 'Init'}) webSocket.send('init'); }; - webSocket.onmessage = function (resopnse) { + webSocket.onmessage = function (response) { const node = document.getElementById('app') - node.innerHTML = resopnse.data + node.innerHTML = response.data node.querySelectorAll('[v-click]').forEach(clickable => { clickable.addEventListener("click", click => { const event = click.target.attributes['v-click'].value diff --git a/live.v b/live.v index 32f3431..1ac301c 100644 --- a/live.v +++ b/live.v @@ -17,14 +17,8 @@ pub fn (mut app App) index() vweb.Result { return $vweb.html() } -pub fn (mut app App) init() { - app.model = &Model{ - count: 3 - } -} - pub fn (mut app App) init_once() { - go start_server(mut app) + go app.start_server() } struct Model { @@ -32,7 +26,7 @@ mut: count int } -fn start_server(mut app App) ? { +fn (mut app App) start_server() ? { mut s := websocket.new_server(30000, '') s.ping_interval = 100 s.on_connect(fn (mut s websocket.ServerClient) ?bool { @@ -46,9 +40,9 @@ fn start_server(mut app App) ? { s.on_message_ref(fn (mut ws websocket.Client, msg &websocket.Message, mut model Model) ? { event := msg.payload.bytestr() - update(event, mut model) + model.update(event) - rendered := view(model) + rendered := model.view() ws.write(rendered.bytes(), msg.opcode) or { panic(err) } }, app.model) @@ -60,25 +54,29 @@ fn start_server(mut app App) ? { s.listen() or {} } -fn update(event string, mut model Model) { +fn (mut model Model) update(event string) { match event { 'init' { + model.count = 3 + } + 'reset' { model.count = 0 } 'inc' { - model.count = model.count + 1 + model.count++ } 'dec' { - model.count = model.count - 1 + model.count-- } else {} } } -fn view(model Model) string { +fn (model Model) view() string { return '
$model.count
+ ' }