In this next example we take a look how we can deal with forms.
If you know normal JavaScript - you should feel at home right away.
1. Start with the usual index.html-file where you define a div-Tag with an id of your choice.
<!-- index.html -->
<div id='myapp'></div>
<script type='module' src='app.js'></script>
2. In app.js, we set up our project as usual.
Unlike common in other frameworks we do not need state for handling inputs (as html already does it).
But we must attach our custom functions so that they can be used in the component.
// app.js
import { RobJSApp } from './Rob.js'
import { Form, post } from './Form.js'
const app = new RobJSApp('myapp')
app.init('app')
app.Form = {}
app.Form.post = post
app.registerComponent(Form, 'form1', [])
app.initialRender(Form, 'form1')
3. Create a component called Form and the function called post in the same file to have things together.
// Form.js
export const post = () => {
// Get the values of the name and message inputs
const nameInput = document.getElementById('name')
const name = nameInput.value
const messageInput = document.getElementById('message')
const message = messageInput.value
// make f.e. an API call to save the post
alert('Name: ' + name + ', Message: ' + message)
// Clear the input fields
nameInput.value = ''
nameInput.blur()
messageInput.value = ''
messageInput.blur()
}
export const Form = (id) => {
return `
<div id=${id}>
<input type='text' id='name' placeholder='Enter name'>
<textarea rows='2' id='message' placeholder='Enter your message'></textarea>
<button onclick='app.Form.post()'>Post</button> <!-- used here -->
</div>
`
};
4. With a bit of styling it looks and works like this.
© - RobJS.org - All rights reserved