Arrays - View Working Example

Arrays in the model can be used to add or remove blocks of HTML automatically with changes to the array. Access to the array must be made to the reference within the model object passed to Modstache. Model references for elements using the array reference the array item object for the context root.

List

The following example adds and removes items from a list by clicking on the buttons.

HTML


        <div id="listExample">
            <div>
                <button {}="onclick:addItem">Click to Add List Item</button>
                <button {}="onclick:removeItem">Click to Remove List Item</button>
            </div>
            <ul>
                <li {}="items;item"></li>
            </ul>
        </div>
    

Javascript


        let listModel = {
            addItem: ({ root }) => () => {
                let list = root.items; list.push({ item: 'Item ' + (list.length + 1) });
            },
            removeItem: ({ root }) => () => {
                if (root.items.length > 0)
                root.items.pop();
            },
            items: []
        };

        _M_.fill(document.getElementById('listExample'), listModel, { removeStache: true });
    

Modified HTML

After clicking the "Add" button three times.


        <div id="listExample">
            <div>
                <button>Click to Add List Item</button>
                <button>Click to Remove List Item</button>
            </div>
            <ul>
                <li>Item 1</li>
                <li>Item 2</li>
                <li>Item 3</li>
            </ul>
        </div>