KnockoutJS: Sign an internal observation of an observed Array sign

In my current project, I decided to try by knockout, and I wonder if the following is possible with it. I am writing an intranet application for some basic list manipulation. The application receives data from the MVC through AJAX. In my callback function, I populate the entries in the 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 is as follows:

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

The observed "active" will change to true when the user marks an entry in the list. So my question is:

So I wonder if itโ€™s possible to subscribe to an โ€œactiveโ€ observable? So, every time a user marks a record, the called user function is called, and the record gets into the observable array marked "notEntries"?

I have already implemented the following functions:

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

But I think that another way would be a cleaner solution, since I also have other ways to โ€œmarkโ€ entries.

+4
source share
1 answer

Make an array markedEntries in computed , which returns an array of lists filtered by your active observable. It will update every time the active state of an element changes.

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

In addition, if listToShow is an observable array , you must set its value at the same time:

 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); } 
+5
source

All Articles