Knockout how to subscribe to every change in an observable array

can you help me get a subscription every time I change my observable collection and every time I change an item . Could not find information about http://knockoutjs.com/documentation/observableArrays.html

$(document).ready(function () {

    var Item = function (isSelected, isEnabled, errorState,
    name, group, processed, errors, state) {
        var self = this;
        self._isSelected = ko.observable(isSelected);
        self._isEnabled = ko.observable(isEnabled);
        self._errorState = ko.observable(errorState);
        self._name = ko.observable(name);
        self._group = ko.observable(group);
        self._processed = ko.observable(processed);
        self._errors = ko.observable(errors);
        self._state = ko.observable(state);
    };

    function ViewModel() {
        var self = this;
        self.SentinelList= ko.observableArray([
        ko.observable(new Item(false, false, false, 'Mail1', 'Mailing', 4, 0, 1)),
        ko.observable(new Item(false, false, false, 'Ident1', 'Identity', 5, 0, 0)),
        ko.observable(new Item(false, false, false, 'Cook', 'Look', 2, 0, 1))]);
    }

    var vm = new ViewModel();

    for (var item in vm.SentinelList) {
        item.subscribe(function () {
            console.log('List changed');
        });
    }

    ko.applyBindings(vm);
});
+4
source share
2 answers

You can use the subscription again in the array:

    self.SentinelList.subscribe(function (changes) {

        changes.forEach(function (change) {
            if (change.status === 'added') {
                 console.log('new item !!');
                 change.value.subcriptions.push(change.value.subscribe(event));
            } else if (change.status === 'deleted') {
                ko.utils.arrayForEach(change.value.subcriptions, function(s) {
                    if(s) s.dispose();
                }
                                     );
                console.log('deleted item !!');
            }
        });

    }, null, "arrayChange");

Watch the violin

+7
source

You can use an external plugin that tracks changes to the view model. For example, KO-Reactor

https://github.com/ZiadJ/knockoutjs-reactor

in this case, the subscription will look like

for(var i = 0; i < vm.SentinelList().length; i++){
    ko.watch(vm.SentinelList()[i], { recurse: true }, function(params, modifiedProperty) { 
        console.log('SentinelList changed');
    });
}

JSFIDDLE

+1
source

Source: https://habr.com/ru/post/1530270/


All Articles