Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
335 views
in Technique[技术] by (71.8m points)

knockout.js - How to conditionally push an item in an observable array?

I would like to push a new item onto an observableArray, but only if the item is not already present. Is there any "find" function or recommended pattern for achieving this in KnockoutJS?

I've noticed that the remove function on an observableArray can receive a function for passing in a condition. I almost want the same functionality, but to only push it if the condition passed in is or is not true.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

An observableArray exposes an indexOf function (wrapper to ko.utils.arrayIndexOf). This allows you to do:

if (myObservableArray.indexOf(itemToAdd) < 0) {
  myObservableArray.push(itemToAdd);
}

If the two are not actually a reference to the same object and you want to run custom comparison logic, then you can use ko.utils.arrayFirst like:

var match = ko.utils.arrayFirst(myObservableArray(), function(item) {
    return itemToAdd.id === item.id;
});

if (!match) {
  myObservableArray.push(itemToAdd);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...