Search code examples
ibm-mobilefirstlodashjsonstore

JSON Store in worklight v6.0


I am trying to integrate the JSONStore standalone app in my multipage application. When I am trying to initialize the collection I am getting the following error "Uncaught TypeError: undefined is not a function". One thing I want to know is, in Worklight version 6.0 I observed that underscore (Lo-Dash) templating was used. But nowhere I found the reference given to the lodash. Also, I didn't find the lodash file anywhere. can anyone please tell me how to do this?
Here is my javascript code

window.$ = window.jQuery = WLJQ; currentPage = {};

currentPage.init = function(WL, jQuery, lodash) { alert("current page ::init called");

'use strict';

//Dependencies
var $ = jQuery,
    _ = lodash;

//CONSTANTS
var PEOPLE_COLLECTION_NAME = 'people',
    KEY_VALUE_COLLECTION_NAME = 'keyvalue',
    INIT_FIRST_MSG = 'PERSISTENT_STORE_NOT_OPEN',
    NAME_FIELD_EMPTY_MSG = 'Name field is empty',
    AGE_FIELD_EMPTY_MSG = 'Age field is empty',
    ID_FIELD_EMPTY_MSG = 'Id field is empty',
    EMPTY_TABLE_MSG = 'No documents found',
    DESTROY_MSG = 'Destroy finished succesfully',
    INIT_MSG = 'Collection initialized',
    ADD_MSG = 'Data added to the collection',
    REPLACE_MSG = 'Document replaced succesfully, call find.',
    REMOVE_MSG = 'Documents removed: ',
    COUNT_MSG = 'Documents in the collection: ',
    CLOSE_ALL_MSG = 'JSONStore closed',
    REMOVE_COLLECTION_MSG = 'Removed all data in the collection',
    LOAD_MSG = 'New documents loaded from adapter: ',
    PUSH_MSG_FAILED = 'Could not push some docs, res: ',
    PUSH_MSG = 'Push finished',
    PASS_CHANGED_MSG = 'Password changed succesfully'; 

$('#init').click(initCollection);      
$('#destroy').click(destroy);    
$('#add-data').click(addData);
$('#find-name').click(findByName);  
$('#find-age').click(findByAge);
$('#find-all').click(findAll);
$('#find-id-btn').click(findById); 
$('#replace').click(replace);
$('#remove-id-btn').click(removeById);

//Log messages to the console and status field
var _logMessage = function (msg, id) {
    //Get reference to the status field
    var status = _.isUndefined(id) ? $('div#status-field') : $(id);

    //Put message in the status div
    status.text(msg);

    //Log message to the console
    WL.Logger.info(msg);
};

//Show JSONStore document in a table
var _showTable = function (arr) {

    if (_.isArray(arr) && arr.length < 1) {
        return _logMessage(EMPTY_TABLE_MSG);
    }

    //Log to the console
    WL.Logger.ctx({stringify: true, pretty: true}).info(arr);

    var
        //Get reference to the status field
        status = $('div#status-field'),

        //Table HTML template
        table = [
            '<table id="user_table" >',
                '<tr>',
                    '<td><b>_id</b></td>',
                    '<td><b>name</b></td>',
                    '<td><b>age</b></td>',
                    '<td><b>json</b></td>',
                '</tr>',
                '<% _.each(people, function(person) { %>',
                    '<tr>',
                        '<td> <%= person._id %> </td>',
                        '<td> <%= person.json.name %> </td>',
                        '<td><%= person.json.age %></td>',
                        '<td><%= JSON.stringify(person.json) %></td>',
                    '</tr>',
                '<% }); %>',
            '</table>'
        ].join(''),

        //Populate the HTML template with content
        html = _.template(table, {people : arr});

    //Put the generated HTML table into the DOM
    status.html(html);
};


//Scroll to the top every time a button is clicked
$('button').on('click', function () {
    $('html, body').animate({scrollTop: 0}, 'slow');
});



function initCollection() {
     console.log("init collection method called");
     alert("init collection method called");
    //Get references to the input fields DOM elements
        var usernameField = $('input#init-username'),
            passwordField = $('input#init-password');

        //Get values from the input fields
        var username = usernameField.val() || '',
            password = passwordField.val() || '';

        //Create the optional options object passed to init
        var options = {};

        //Check if a username was passed
        if (username.length > 0) {
            options.username = username;
        }

        //If if a password was passed
        if (password.length > 0) {
            options.password = password;
        }

        //JSONStore collections metadata
        var collections = {};

        //Define the 'people' collection and list the search fields
        collections[PEOPLE_COLLECTION_NAME] = {

            searchFields : {name: 'string', age: 'integer'},

            //-- Start optional adapter metadata
            adapter : {
                name: 'people',
                add: 'addPerson',
                remove: 'removePerson',
                replace: 'replacePerson',
                load: {
                    procedure: 'getPeople',
                    params: [],
                    key: 'peopleList'
                }
            }
            //-- End optional adapter metadata
        };

        //Define the 'keyvalue' collection and use additional search fields
        collections[KEY_VALUE_COLLECTION_NAME] = {
            searchFields : {},
            additionalSearchFields : { key: 'string' }
        };

        //Initialize the people collection
        WL.JSONStore.init(collections, options)

        .then(function () {
            _logMessage(INIT_MSG);
            _callEnhanceToAddKeyValueMethods();
        })

        .fail(function (errorObject) {
            _logMessage(errorObject.msg);
        });
}

Thanks in advance

regards
V.H.C


Solution

  • I observed that underscore(loadash) templating was used. But nowhere I found the reference given to the loadash. Also, I didn't find the loadash file anywhere. can anyone please tell me how to do this?

    You can build your own version of lodash or use underscore.

    The version of lodash used by worklight is in the WL_ variable. Looking at your code, maybe you want to replace _ = lodash with _ = WL_. Alternatively when you bring your own version lodash or underscore it will be assigned to the _ variable automatically.

    Alternatively, you can use other string template libraries like Handlebars.js or basic string interpolation by modifying the String prototype.