+

Search Tips   |   Advanced Search

JavaScript module example

View an example of how to use WL.Logger to add log messages to a JavaScript module.

This example demonstrates how to use WL.Logger to add log messages to a JavaScript module using these methods:

The example uses the default initOptions.js file for IBM Worklight v6.0. This list contains some of the principles that are demonstrated by the example:

myApp.Greeter.js

var myApp = myApp || {};
myApp.Greeter = (function (WL) {
    //ECMAScript 5 strict mode
    'use strict';
    //Dependencies
    var WL_LOGGER = WL.Logger;
    //... other dependencies     //Constants
    var PKG_NAME = 'myApp.Greeter';
    var DEFAULT_NAME = 'Stranger';
    //... other constants
    //LogInstance local to this module     var l = WL_LOGGER.create({pkg: PKG_NAME});
    //Private function to the module that does validation and alerts a name     var __alertName = function (name) {
        l.debug('Calling __alertName with name =', name);
        if (typeof name !== 'string' || name.length < 1) {
            l.warn('Name was not a string or empty string, setting name to', DEFAULT_NAME);
            name = DEFAULT_NAME;
        }
        else if (name === '*') {
            throw new Error('Name can not be *');
        }
        //Assume 'alert' is always a global function that exists
        alert('Hello ' + name);
        l.debug('Done calling __alertName');
    };
    //Public API function that does initialization
    var _start = function () {
        l.info('Started', PKG_NAME ,'module');
        //... init code         
    };
    //Public API function that alerts 'Hello [name]'
    var _sayHello = function (name) {
        l.debug('Starting _sayHello');
        try {
            __alertName(name);
        } catch (e) {
            //Log any errors
            l.error(e);
        }
        l.debug('End _sayHello');
    };
    //Public API     return {
        start : _start,     sayHello: _sayHello
    };
}(WL)); //Pass global variables to the module

main.js

function wlCommonInit () {
    myApp.Greeter.start(); //Start our application's greeter module     myApp.Greeter.sayHello('Carlos'); //should alert 'Hello Carlos'
    myApp.Greeter.sayHello(); //should alert 'Hello Stranger'
    myApp.Greeter.sayHello('*'); //should log an error
}

index.html

<!-- ... other html tags -->
<body id="content" style="display: none;">
    <!-- ... application UI -->
    <script src="js/initOptions.js"></script>
    <script src="js/myApp.Greeter.js"></script>
    <script src="js/main.js"></script>
    <!-- ... other script tags -->
</body>

Figure 1. Log output


Parent topic: Configure the MobileFirst Logger