Skip to main content
1 de 3
Amadeu Antunes
  • 3,4mil
  • 3
  • 31
  • 66

Porque esta a returnar false?

A duvia é a seguinte: Quando clico no botão Add To List este executa a função addToList que por sua vez executa a função isThere que está a a returnar false e este é exactamente o que não entendo.

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>

Amadeu Antunes
  • 3,4mil
  • 3
  • 31
  • 66