I have a below code for knockout binding:
HTML:
<div data-bind="visible: people().length > 0">
<div data-bind="foreach: people"> <span data-bind="text: title"></span>
<span data-bind="text: forename"></span>
<span data-bind="text: surname"></span>
<button data-bind="click: $root.removePerson">Remove</button>
<br />
</div>
</div>
<div data-bind="with: Person">
<input type="text" data-bind="value: title" />
<input type="text" data-bind="value: forename" />
<input type="text" data-bind="value: surname" />
<button data-bind="click: $root.addPerson">Add</button>
</div>
Javascript:
var my = my || {};
Person = function () {
var self = this;
self.title = ko.observable(null);
self.forename = ko.observable(null);
self.surname = ko.observable(null);
};
my.vm = function () {
var people = ko.observableArray([]),
addPerson = function (jh) {
people.push(jh);
},
removePerson = function (jh) {
people.remove(jh);
};
return {
people: people,
addPerson: addPerson,
removePerson: removePerson
};
}(new Person());
ko.applyBindings(my.vm);
I am struggling to add Person object into an observable array (people) and display it on top to create an array of people with add and remove functionality in it.
jsFiddle here
Can someone please advise what am I missing?
Update: I have tidied up code a little bit, now the issue can be seen on fiddle, that adding a single object update all the array objects and removing an object removes all the objects from array which is the problem. Thank for the help.
people = function (p)rather thanaddPerson = function (p)? Are you seeing errors or what problem are you having?