Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Knockout, how to subscribe to every change in observableArray

can you help me to get subscription on every change of my observable collection and on every item change. Didn't find information on 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);
});
like image 668
Ark Avatar asked Mar 05 '14 15:03

Ark


People also ask

What does Ko unwrap do?

unwrapObservable(item) Looking at the code, that call basically checks to see if item is an observable. If it is, return the value(), if it's not, just return the value.

What is Ko observableArray?

An observableArray just tracks which objects it holds, and notifies listeners when objects are added or removed.

What is Ko computed in knockout JS?

ko. computed( evaluator [, targetObject, options] ) — This form supports the most common case of creating a computed observable. evaluator — A function that is used to evaluate the computed observable's current value. targetObject — If given, defines the value of this whenever KO invokes your callback functions.


1 Answers

You can use the subscribe againt 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");

See fiddle

like image 167
Damien Avatar answered Sep 22 '22 09:09

Damien