0
The duvia is as follows:
When I click the button Add To List this executes the function addToList
which in turn performs the function isThere
who is returning false and this is exactly what I don’t understand.
function Person(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
function isThere(list, p) {
var lista = list;
var person = p;
var flag = false;
var i = 0;
for (i = 0; i < list.length; i = i + 1) {
if (lista()[i].firstName == person.firstName) {
flag = true;
}
}
return flag;
}
function AppViewModel() {
this.firstName = ko.observable("Bert");
this.lastName = ko.observable("Bertington");
this.fullName = ko.computed(function() {
return this.firstName() + " " + this.lastName();
}, this);
this.capitalizeLastName = function() {
var currentVal = this.lastName();
this.lastName(currentVal.toUpperCase());
}
this.isthere = ko.observable("false");
this.persons = ko.observableArray([]);
this.addToList = function() {
var firstName = this.firstName();
var lastname = this.lastName();
var p = new Person(firstName, lastname);
this.persons.push(p);
this.isthere(isThere(this.persons, p));
};
}
ko.applyBindings(new AppViewModel());
this.capitalizeLastName = function() {
var currentVal = this.lastName();
this.lastName(currentVal.toUpperCase());
};
.row {
display: flex;
flex-direction: row;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.5.0/knockout-min.js"></script>
<div class="row">
<div>
<p>First name: <input data-bind="value: firstName" /></p>
<p>Last name: <input data-bind="value: lastName" /></p>
<button data-bind="click: capitalizeLastName">Go caps</button>
<button data-bind="click: addToList">Add To List</button>
<p data-bind="text: isthere"></p>
<p data-bind="text: firstName"> </p>
<p data-bind="text: lastName"></p>
<p data-bind="text: fullName"></p>
</div>
<div>
<table style="background-color:blue">
<thead>
<tr>
</tr>
</thead>
<tbody data-bind="foreach: persons">
<tr>
<td data-bind="text: firstName"></td>
<td data-bind="text: lastName"></td>
</tr>
</tbody>
</table>
</div>
</div>
[Just because you can help someone]
Probably because the condition of
if
is not being satisfied.– Sam
That’s what I don’t understand why!
– Amadeu Antunes
Puts a
console.log(lista()[i].firstName, person.firstName)
before IF and see if the values are correct– Sam