logo

Example: Components with Parameters

To make our components even more versatile we can equip them with parameters.

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.
But now when we register our components, we pass further arguments, in this case a name and a function name.
We can create custom functions by simply attaching an empty object to our app and attach a function to that. By doing it like that we avoid naming conflicts.
It is not necessary to define the functions in this file as we did for this simple example. Normally you would do this in a seperate file and just import it to keep app.js as clean as possible.

    
// app.js
import { RobJSApp } from './Rob.js'
import { Dog } from './Dog.js'
import { Dogshouse } from './Dogshouse.js'

const app = new RobJSApp('myapp')
app.init('app')

app.Dog = {}
app.Dog.maxSound = (name) => alert('Wuff, I am ' + name)
app.Dog.bellaSound = (name) => alert('Wau, I am ' + name)

app.registerComponent(Dog, 'dog1', [], 'Max', 'app.Dog.maxSound')
app.registerComponent(Dog, 'dog2', [], 'Bella', 'app.Dog.bellaSound')

app.initialRender(Dogshouse)
    
    

3. Next we create our components Dog and Dogshouse.
As Dogshouse is essentially only a Wrapper for two Dog components and as it contains no state, it does not need to be registered as a component and also does not need an id.
The Dog component on the other hand receives additionally to an id also the name and sound and even uses the name as an argument for the sound function.
Notice that in Dogshouse the Dogs only receive their id as an argument. All other arguments are passed automatically over the registerComponent function from app.js.

    
// Dog.js
export const Dog = (id, name, sound) => {
  return `
      <div id=${id}>
        <p>Dog's Name: ${name}</p>
        <button onclick='${sound}("${name}")'>Make Sound</button>
      </div>
  `
};

// Dogshouse.js
import { Dog } from './Dog.js'

export const Dogshouse = () => {
    return `
        <div>
          ${Dog('dog1')}
          ${Dog('dog2')}
        </div>
    `
};
    
    

4. With a bit of styling it looks and works like this.

© - RobJS.org - All rights reserved