2021.2

Table Of Contents
Example
Saving and restoring Camera widgets
This example demonstrates a way to save and restore dynamically added Camera widgets.
How to add Camera widgets is explained in another topic: "Dynamically adding COTG
widgets" on page611.
When a user takes or selects a picture with a Camera widget, the COTG app stores the path to
the image that was taken or selected in a hidden input. This is the path to the image on the
device that runs the COTG app. On submitting the Form the COTG app replaces this value - the
path - with the actual image data.
In this example the hidden fields of dynamically added Camera elements have got the .camera-
dyn class. In the event handler for the olcotgsavestate event, the jQuery each() method is
used to iterate over all inputs that have this class, storing their name and value in an object.
Next, this object is stored - in JSON format - in the event.detail.state data with the key my-
camera-data.
window.addEventListener('olcotgsavestate', function(event) {
var camObj = {};
$('input.camera-dyn').each(function(){
var camera = $(this).attr('name');
var val = $(this).val();
camObj[camera] = val;
});
event.detail.state['my-camera-data'] = JSON.stringify(camObj);
});
In the olcotgrestorestate event handler the previously stored JSON is read from the
event.detail.state and parsed into a JavaScript object. A for ... in loop is then used to
iterate over the keys (the camera names) in that object. Inside this loop the cameras are added
by calling the addCamera() function with the ID and value (the path to the picture) of each
Camera element. Subsequently the restore-state.cotg event of the new widget is called to
make sure that the thumbnail of the picture is shown and the Clear button becomes visible.
window.addEventListener('olcotgrestorestate', function(event) {
var json = JSON.parse(event.detail.state['my-camera-data']);
for (var cameraID in json) {
var value = json[cameraID];
addCameraWidget(cameraID,value);
$('#' + cameraID).trigger('restore-state.cotg',
event.detail.state);
}
Page 618