Rudy Hinojosa
Rudy Hinojosa

Reputation: 1468

Removing multiple keys based on a stored field value

I have several records with a unique identifier that I want to drop after the form has performed it's ajax post. Let's assume I have 5 records in my goinstant storage and the common field is xkey and the value in it contains 123*. My question is how can I remove multiple keys cleanly? Any examples would be tremendously helpful.

Slukeheart has the correct answer with best practice in mind: I found a working solution as well, but I'm giving the correct answer credit to Slukeheart. This is what I found to work at the same time as the solution was posted today:

$.ajax({
  url: './angtest',
  type: 'POST',
  contentType: 'application/json',
  data: JSON.stringify({ model: mymodelobj }),
  success: function (result) {
     //handleData(result);
     //remove old record entries to prevent table bloat.
  $scope.person = $goQuery('person', { xkey:  @Html.Raw(json.Encode(ViewBag.xkey1)) }, { limit: 30 }).$sync();
  $scope.person.$on('ready', function () {
    var tokill = $scope.person.$omit();
    angular.forEach(tokill, function(person,key) {
        $scope.person.$key(key).$remove();
    })
  });
  }

});

Upvotes: 0

Views: 47

Answers (1)

Slukehart
Slukehart

Reputation: 1037

GoAngular & Angular both utilize promises, which provide an effective way of managing asynchronous method calls (like key.$remove). GoAngular uses the Q promise library and Angular uses a subset of Q, aptly named $q.

I've just briefly summarized removing multiple keys with a shared xkey below, I've also prepared a more detailed working plunkr.

angular
  .module('TestThings', ['goangular'])
  .config(function($goConnectionProvider) {
    $goConnectionProvider.$set('https://goinstant.net/mattcreager/DingDong');
  })
  .controller('TestCtrl', function($scope, $goKey) {
    var uid = 'xkey'; // This is created dynamically in the working example

    // Create a collection or promises, each will be resolved once the associated key has been removed.  
    var removePromises = ['red', 'blue', 'green', 'purple', 'yellow'].map(function(color) {
      return $goKey('colors/' + color + '/' + uid).$remove();
    });

    // Once all of the keys have been removed, we log out the destroyed keys
    Q.all(removePromises).then(function(removedColors) {
      removedColors.forEach(function(color) {
        console.log('Removed color with key', color.context.key);
      });
    }).fail(function() {
      console.log(arguments); // Called if a problem is encountered
    });
  });

Upvotes: 6

Related Questions