2013-11-07 2 views
0

Я пытаюсь интегрировать автономное приложение JSONStore в своем многостраничном приложении. Когда я пытаюсь инициализировать коллекцию, я получаю следующую ошибку: «Uncaught TypeError: undefined не является функцией». Одна вещь, которую я хочу знать, - в Worklight версии 6.0 я заметил, что используется шаблон подчеркивания (Lo-Dash). Но нигде я не нашел ссылку на lodash. Кроме того, я не нашел файл lodash в любом месте. может ли кто-нибудь рассказать мне, как это сделать?
Это мой javascript-кодJSON Store in worklight v6.0

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

currentPage.init = function (WL, jQuery, lodash) { alert («текущая страница :: init вызвана»);

'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); 
     }); 
} 

Заранее спасибо

С уважением
V.H.C

ответ

1

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?

Вы можете создать свою собственную версию lodash или использовать underscore.

Версия lodash, используемая прожектором, находится в переменной WL_. Если вы посмотрите на свой код, возможно, вы захотите заменить _ = lodash на _ = WL_. Альтернативно, когда вы приносите свою собственную версию lodash или подчеркивание, она автоматически присваивается переменной _.

В качестве альтернативы вы можете использовать другие библиотеки шаблонов строк, такие как Handlebars.js или basic string interpolation, путем изменения прототипа String.

+0

Если я не использую свою собственную версию loadash или handlebars, тогда мне не нужно давать ссылку правильно? Я просто использую тот, который приведен в учебнике. В этом случае мне не нужно давать какие-либо ссылки, и я могу напрямую использовать все, что присутствует в учебнике, прямо? – user2542428

+1

Вы можете напрямую использовать WL_, например, вызвать: WL_.template вместо _.template. – cnandreu

+0

Подчеркнутый (loadash) поставляется в комплекте с Worklight как jQuery? Если да, то какая версия подчеркивания используется? – user2542428

Смежные вопросы