ko.utils.removeItem vs. ko.observableArray([]).remove(item)?

2,686 views
Skip to first unread message

Kevin Van Lierde

unread,
Jan 10, 2015, 8:28:48 PM1/10/15
to knock...@googlegroups.com
ko.observableArray([]).remove(item) allows one to directly execute the function to return the item inside, or just pass the item immediately, eg

self.children.remove(function(item) { return data === item; });
self.children.remove(data);

whereas, ko.utils.arrayRemoveItem(ko.observableArray([]), item) requires one to manually iterate over the array and find the desired item.
So my questions is why bother with the second at all?
  • Are there any cases in which nr.2 would be preferable to nr.1?
  • Is there any difference in effect of executing either, except perhaps performance?

For reference, from the documentation on Github, these are the 2 concerned functions: 
 
ko.observableArray([]).remove(item)

ko.observableArray['fn'] = {
  'remove': function (valueOrPredicate) {
      var underlyingArray = this.peek();
      var removedValues = [];
      var predicate = typeof valueOrPredicate == "function" && !ko.isObservable(valueOrPredicate) ? valueOrPredicate : function (value) { return value === valueOrPredicate; };
      for (var i = 0; i < underlyingArray.length; i++) {
          var value = underlyingArray[i];
          if (predicate(value)) {
             if (removedValues.length === 0) {
                 this.valueWillMutate();
             }
             removedValues.push(value);
             underlyingArray.splice(i, 1);
             i--;
          }
      }
[...]
}

ko.utils.arrayRemoveItem(ko.observableArray([]), item)

arrayRemoveItem: function (array, itemToRemove) {
   var index = ko.utils.arrayIndexOf(array, itemToRemove);
   if (index > 0) {
      array.splice(index, 1);
   }
   else if (index === 0) {
      array.shift();
   }
},

Gunnar Liljas

unread,
Jan 11, 2015, 9:17:57 AM1/11/15
to knock...@googlegroups.com
ko.utils.arrayRemoveItem is just a utility function to remove items from arrays. Plain JS arrays.

ko.observableArray([]).remove(item) is the method which removes items in observable arrays, by value or predicate, and triggers the resulting change notifications.

There's no reason to use ko.utils.arrayRemoveItem(ko.observableArray([]), item), unless you want to avoid the change notifications.

/G




--
You received this message because you are subscribed to the Google Groups "KnockoutJS" group.
To unsubscribe from this group and stop receiving emails from it, send an email to knockoutjs+...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply all
Reply to author
Forward
0 new messages