Monday, 26 October 2020

Mount a component in pug template

I am importing the apprun script in an pug html template so I can use its functions. (reference) Where can I write JavaScript to mount this Component in a pug template after it is rendered?

Here is my pug file:

extends layout

block append scripts
  script(src='/javascripts/function.js')
  script(src="https://unpkg.com/apprun/dist/apprun-html.js")
  body
    script(src='/javascripts/frontendapp.js')
  if dev
    script(src="https://unpkg.com/apprun@latest/dist/apprun-dev-tools.js")

  script.
   app.on('//ws:', (event, state) => {
    const msg = {event, state}
    ws.send(JSON.stringify(msg))
   })
block content
  h1 MApp list - #{route}
  P
    label 現在日期:
    input.form-control(type="text" value="2020/01/01" size="10" placeholder="")#T_YMD
    label 時間: 
    input.form-control(type="text" value="00:00:00" size="8" placeholder="")#T_HMS
  P
    label 篩選器:
    input.form(type="date")#T_FYMD
    input.form-control(type="submit", text="提交")
  input.form-control(type="submit", value="ACK")
  form(method="post" action="")
    p
      label(for="name") URL: 
      textarea(name="alert_m" rows="5" cols="60" required="")
      input(type="submit")

the component:

const ws = new WebSocket(`ws://${location.host}`)

//front-end application state
const state = {
    msg: 'Test Message',
    data: [],
    continue: true,
}
//client-side listenr 
ws.onmessage = (msg) => {
    console.log(msg)
    const { event } = JSON.parse(msg.data)
    app.run(event, JSON.parse(msg.data))
}

//views 
const view = (state) => {
    return
    `<div>
        <h1>MApp list</h1>
        <p></p>
        <table>
            <thead>
                <tr>
                    ${headers.map((c) => `<th>${c}</th>`)}
                </tr>
                <tr>
                    ${state.data.map(c => `<td>${c}</td>`)}
                </tr>
            </thead>
        </table>
    </div>`
}


//frontend events
const update = {
    'refresh': (state, data) => {
        let { records } = data
        if (records) {
            state.data = records
        }
    },
    'ack': (state) => { },
    'delete': (state) => { },
    'alert': (state) => { },
    'shutdown': (state) => {
        ws.close()
        alert("Recieved shutdown from server. Refresh to continue.")
    },
    'echo': (state, data) => {
        console.log(data)
        let { msg } = data
        if (msg) {
            state.msg = msg
        }
        alert(`Received echo message from server: ${state.msg}`)
    }
}

app.start(document.body, state, view, update)


from Mount a component in pug template

No comments:

Post a Comment