opp
opp

Reputation: 1020

KnockoutJS: Subscribe inner observable of observableArray entry

For my current project I decided to try out knockout and I'm wondering if the following is possible with it. I'm writing an intranet app for some basic list manipulations. The app gets data from a MVC Controller via AJAX. In my callback function I'm filling the entries to an observable Array as follows:

function showData(data) { // ajax callback
   $.each(data, function (key, dmsEntry) {
        vm.listToShow.push(new dmsList(dmsEntry));  // adds new dmsEntry into observableArray
   });
}

The dmsList function looks as follows:

function dmsList(dmsEntry) {
       return {
          a: dmsEntry.a,
          b: dmsEntry.b,
          active: ko.observable(false)
       }
 }

The observable "active" will change to true when a user marks a list entry. So my question is:

So I'm wondering if it's possible to subscribe to the "active" observable? So every time a user marks an entry a custom function gets called and the entry gets pushed in a "markedEntries" observable array?

I've already implemented the functionality with:

<input type="checkbox" data-bind="checked: active, click: $root.addToActionQueue" />

But I think the other way would be a much cleaner solution as I also have other ways to "mark" entries.

Upvotes: 4

Views: 1279

Answers (1)

Mike B
Mike B

Reputation: 2706

Make your markedEntries array into a computed that returns the list array filtered by your active observable. It will update every single time a item's active state changes.

var markedEntries = ko.computed(function() {
   return ko.utils.arrayFilter(this.items(), function(item) {
       return item.active();
   });
});

Also, assuming listToShow is an observable array, you should be setting its value all at once like this:

function showData(data) { //ajax callback
    var list = [];
    $.each(data, function (key, dmsEntry) {
         list.push(new dmsList(dmsEntry); //adds new dmsEntry in observableArray         
    });
    vm.listToShow(list);
 }

Upvotes: 5

Related Questions