0

I am trying to add elements in an observableArray but here I have problem that newly added element replace last elements.

var bugTracker = function() {
  var self = this;
  self.bugName = ko.observable(''),
    self.bugList = ko.observableArray([
      {name:"Abc",age:27},{name:"Dooo",age:27},{name:"Usss",age:27},{name:"Yeess",age:27}
    ])
  self.addBug = function() {
    var newBug = {
      name: self.bugName,
      age: 86
    }
    self.bugList.push({
      name: self.bugName,
      age: 89
    });
  }
  self.removeBug = function() {
    self.bugList.remove(this);
  }
}
bugTracker.bugList
$(function() {
  ko.applyBindings(new bugTracker());
});

HTML:

<input type="text" data-bind="value : bugName" >
<input type="button" data-bind="click: addBug" value="Add Bug"/>
<ol data-bind="foreach : bugList">
    <li data-bind="text : name" >
    </li>
</ol>

Output :

enter image description here

1 Answer 1

1

You need to invoke bugName as a function to get the current value, and you can discard the double creation of newBug, so:

self.addBug = function() {
  var newBug = {
    name: self.bugName(),
    age: 86
  }
  self.bugList.push(newBug);
}

See this working jsfiddle.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.