Search code examples
javascriptibm-mobilefirstjsonstore

adding documents to worklight jsonstore in a loop


I want to dynamically generate list entries and add them to my local store as jsonstore documents at the same time.

When I do it like this :

     var j=0;
       while(j<7) {

        /* populating our jsonstore */   
        accessor.add({stuff_to_add})
        .then(function(){})

        /* showing it to the user */
        $('<li>').attr({attributes}).html('html').appendTo('element');   
        j++;

       }

only one document gets added because I think worklight does not put the add request in a queue automatically and cancels the last one if the previous is not resolved or sth along those lines.

So when I do it like this :

      var j=0;
       while(j<7) {

        /* populating our jsonstore */   
        accessor.add({stuff_to_add})
        .then(function(){

        /* showing it to the user */
        $('<li>').attr({attributes}).html('html').appendTo('element');   
        j++;   })

       }

Mozilla completely crashes and does not even succeed in stopping the script I do not understand why because it should only call the add function a number of times = (time to call (accessor.add) / time to loop) which should be finite.

EDIT : actually if we make the assumption worklight does not put the documents in the add queue, the initial add request is replaced every time the loop loops and it never completes which explains the crash.

EDIT 2 : trying something with a recursive function calling itself until j reaches 7 instead of loop


Solution

  • The add API can take an array of JSON objects, for example:

    var data = [{name: 'carlos'}, {name: 'mike'}];
    
    WL.JSONStore.get('collection').add(data)
    
    .then(function () {
    
      /*update the UI here*/
    
      var len = data.length;
      while (len--) {
        console.log(data[len].name);
      }
    
    })
    
    .fail(function (err) {
      /*handle failure*/
    });