Calculating a data value

Data values can be provided by a function instead of a direct value. For example, the following shows how to modify a button's text depending on other values in the provided data

HTML

    <button {}="btn.label;onclick:btn.onclick">Create</button>

Javascript

    var state = {
         model: { id: 1 },
         btn: {
             label: (ctx, element, parent) => { return (ctx.root.model.id !== 0) ? 'Update' : ctx.element.innerHTML},
             onclick: (ctx, element, parent) => () => alert('Button has been clicked')
          }
    };

Context

Functions in the data are passed an object parameter with the context. It has the following properties:

  • element - the DOM element being processed
  • root - the data object passed into Modstache or the object in an array used to fill the template
  • parent - the parent object containing the data function
  • key - the key in data containing the data function
  • array - the containing array, if used
  • base - the original object passed into Modstache
  • parentage - array of root objects - useful with child arrays

In the example above, ctx would contain the following values for the btn.label specifier:

Javascript

    ctx = {
         element: button_DOM_Element,
         root: state,
         parent: state.btn,
         key: 'label',
         array: null,
         base: state,
         parentage: [ state ]
    };

Additional parameters for the element and parent values are passed to the function to simplify access.