/ / Ako skontrolovať zmenu observableArray - javascript, jquery, knockout.js

Ako skontrolovať pozorovateľnú zmenuArray - javascript, jquery, knockout.js

Používam knockout_2.0.js. Mám pozorovateľné pole, na ktorom som nastavil predplatné. Páči sa mi to :

 var Items = ko.observableArray();


Items.subscribe(function(newValue){

//I want to check here whether the item is Added or Deleted from the array

});

Ako to môžem urobiť?

odpovede:

0 pre odpoveď č. 1

Ak chcete len vedieť, či bolo niečo pridané alebo odstránené, môžete to ľahko sledovať pomocou premennej na vonkajšom rozsahu.

var items = ko.observableArray();

var itemLen = items.length;

items.subscribe(function (newValue) {

//I want to check here whether the item is Added or Deleted from the array
if (itemLen > items.length) {
// Item removed
} else if (itemLen < items.length) {
// item added
} else {
// something else was modified
}
itemLen = items.length;
});

0 pre odpoveď č. 2

Vyskúšajte nižšie uvedený kód, ktorý vám môže pomôcť.

var Items = ko.observableArray();
var ItemsLength = ko.observableArray();

this.ItemsLength = ko.computed({
read: function() {
return this.Items().length;
}
});

this.ItemsLength.subscribe(function(newValue){

//you will get control over here whether the
item is Added or Deleted from the array

});