Why does duplicate verification Artistalways return false?
Check out the JSFiddle for a demo.
Knockout code
$(function() {
function Artist(name) {
this.name = name;
}
function ViewModel() {
var self = this;
self.favoriteArtists = ko.observableArray([]);
self.artistToAdd = ko.observableArray("");
self.addArtist = function () {
var newFavoriteArtist = new Artist(self.artistToAdd());
console.log("New Favorite Artist: " + newFavoriteArtist.name);
var artistExists = self.favoriteArtists.indexOf(newFavoriteArtist) > 0;
console.log("Artist Exists: " + artistExists);
if(!artistExists) {
self.favoriteArtists.push(newFavoriteArtist);
console.log("A new artist has been added:" + self.artistToAdd());
} else {
console.log("Artist already in favorites.");
}
};
}
ko.applyBindings(new ViewModel());
});
HTML
<h1>Favorite Artists</h1>
<p>Currently, your favorite artists include:</p>
<ul data-bind="foreach: favoriteArtists">
<li> <span data-bind="text: name"></span>
</li>
</ul>
<p>Enter the name of a new artist:</p>
<input data-bind="value: artistToAdd" />
<button data-bind="click: addArtist">Add</button>
source
share