Calculations - View Working Example

The model can calculate values for the element property or attribute by using a function assigned to the model property that returns the computed result. The function is passed the context, element and parent object. In the example, the root property of the context is used to access the model object.

Calculating the full name

The following example calculates the full name in the model, first name and last name.

HTML


        <div id="name">
            <b>First Name:</b> <span {}="firstName"></span><br />
            <b>Last Name:</b> <span {}="lastName"></span><br />
            <b>Full Name:</b> <span {}="fullName"></span>
        </div>
    

Javascript


        let nameModel = {
        firstName: 'John',
        lastName: 'Doe',
        fullName: ({ root }) => root.firstName + ' ' + root.lastName
        };

        _M_.fill(document.getElementById('name'), nameModel, { removeStache: true });
    

Modified HTML


        <div id="name">
            <b>First Name:</b> <span {}="firstName">John</span><br>
            <b>Last Name:</b> <span {}="lastName">Doe</span><br>
            <b>Full Name:</b> <span {}="fullName">John Doe</span>
        </div>
    

Display current time

The following example calculates and displays the current time. In this example, the time property is replaced with a function returning the current time after setting up an interval timer. The property is assigned to itself on each interval in order to refresh the calculation.

HTML


        <div id="time">
        <b>Current Time:</b> <span {}="time"></span>
        </div>
    

Javascript


        let timeModel = {
            time: (ctx) => {
            setInterval(() => { ctx.parent.time = ctx.parent.time; }, 1000); // set up automatic update every second
            ctx.parent.time = () => { return (new Date()).toLocaleTimeString(); }; // modify time property to get current time
            return ctx.parent.time();
            }
        };

        _M_.fill(document.getElementById('time'), timeModel);
    

Modified HTML


        <div id="time">
        <b>Current Time:</b> <span {}="time">12:56:43 PM</span>
        </div>