Question

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.

Was it helpful?

Solution

The issue that you are having is that you are always dealing with a single instance of a Person. So, you are adding, updating, and removing the same instance.

A better approach might be to use something like a personForEditing observable that contains a new person. Then, when doing addPerson you would add this person to the observableArray and replace personForEditing with a new instance for the next entry. Based on your code something like:

my.vm = function () {
    var people = ko.observableArray([]),
        addPerson = function (jh) {
            people.push(jh);
            personForEditing(new Person());
        },
        removePerson = function (jh) {
            people.remove(jh);
        },
        personForEditing = ko.observable(new Person())
    return {
        people: people,
        addPerson: addPerson,
        removePerson: removePerson,
        personForEditing: personForEditing
    };
}();

updated sample: http://jsfiddle.net/rniemeyer/xms4d/

OTHER TIPS

You are reassigning the variable people.

First it is set to an observable then to a function.

So the fault is here:

var people = ko.observableArray([]),
    people = function (p) {
        people.push(p);
    }, ... ;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top