0

is it possible to fire a function when observable array is modified? my goal here is to notify me if my observable array is modified to do some logics on my current application

this is my view model it has a observable array inside it

WT.BM.BarsViewModel = function () {
    var self = this;
    self.BarsDataHolder = ko.observableArray([]);
};

i just want to fire a function to notify me if self.BarsDataHolder has been modified

any ideas?

Don
  • 131
  • 1
  • 10
  • Do you want to be notified when an item is added or removed or when one of its items changed? In any case you should read the documentation: http://knockoutjs.com/documentation/observables.html#explicitly-subscribing-to-observables – nemesv Nov 26 '14 at 07:38

1 Answers1

2

You can subscribe to any ko.observable or ko.observable array.

WT.BM.BarsViewModel.BarsDataHolder.subscribe(function(newArray) {
   console.dir(newArray);
});

you can find this in the knockout documentation on the observables page

Beartums
  • 1,340
  • 1
  • 10
  • 15
  • 1
    The argument passed to the `newValue` parameter is the array itself, not the new value. – haim770 Nov 26 '14 at 07:53
  • Thanks. I just noticed that. If Don needs to know hat the new value is, he can save the array before changes are made and compare it, though I'm not sure if he cares what the change is, necessarily. In any case, I've changed the answer to better reflect your comment – Beartums Nov 26 '14 at 07:59
  • Yep. That's a better answer. Thanks – Beartums Nov 26 '14 at 08:03
  • Hi i've tried this code but it seems has an error i also tried to instantiate my view model and through that i access the observable array and subscribe and the error is gone but whenever i push a data into the array the function that i subscribe is not firing at all – Don Nov 26 '14 at 08:08
  • Can you show the code? I tried this on the knockout tutorials site and it worked fine. [Here](http://jsfiddle.net/aqbbs3q4/) is a fiddle that works. – Beartums Nov 26 '14 at 08:11