Working with arrays

Working with arrays

Working with arrays of data in maquette can simply be accomplished by using the javascript map function, mapping from the data to the virtual DOM nodes directly. This looks as follows:

It does get a little more complex if your items need to maintain state or event handlers. For performance reasons maquette forces you to reuse event handler functions on every render. So you need to keep track of them. A good approach is to map the data to components and have these components render the virtual DOM. The following example shows how to do this.

There is one more advanced usecase. What if your items maintain state or event handlers but the underlying data can also get updated? This could be the case if you use real-time communication or periodic refreshes. Maquette provides the createMapping function to keep your list of components synchronized with the underlying data. The algorithm that maquette uses to update the array of components may look somewhat similar to how maquette updates the real DOM in order to reflect the virtual DOM, but there are subtle differences. For example, the components will be reordered, instead of being removed and recreated.

The createMapping function serves the same purpose as the Javascript map function, but with the ability to call map multiple times and reusing the previous results where possible. The code below demonstrates this behavior.

More information about createMapping can be found in the API documentation.