Code_Ed_Student
Code_Ed_Student

Reputation: 1190

Counting the number of contacts and remove contact button

I am currently learning and playing around with the use of the knockout js framework. I have a basic set of fields for contacts. I am able to add contacts without any problems. But there are two things I am having difficulties figuring out. First, a button to remove a contact(both name and phone). Second, a way to count number label the contacts. I set a label Person and try using data-bind: $index to see if I could get Person # 1, Person # 2, etc but it did not work. JSFIDDLE

var ContactsModel = function(contacts) {
    var self = this;
    self.contacts = ko.observableArray(ko.utils.arrayMap(contacts, function(contact) {
        return { firstName: contact.firstName, lastName: contact.lastName, phone: contact.phone, alt_phone: contact.alt_phone };
    }));

    self.addContact = function() {
        self.contacts.push({
            firstName: "",
            lastName: "",
            phone: "",
            alt_phone: ""
        });
    };

    self.removeContact = function(contact) {
        self.contacts.remove(contact);
    };

    self.addPhone = function(contact) {
        contact.phones.push({
            number: ""
        });
    };

    self.removePhone = function(phone) {
        $.each(self.contacts(), function() { this.phones.remove(phone) })
    };

    self.save = function() {
        self.lastSavedJson(JSON.stringify(ko.toJS(self.contacts), null, 2));
    };

    self.lastSavedJson = ko.observable("")
};

ko.applyBindings(new ContactsModel(initialData));

Upvotes: 0

Views: 49

Answers (1)

Akhlesh
Akhlesh

Reputation: 2399

$index is not working because you are using knockout2.0.0 it doesn't have $index observable. and for deleting the contact add this code

<a href="javascript:void(0)" data-bind="click: $parent.removeContact">Remove</a>

working code http://jsfiddle.net/dLbY7/12/

Upvotes: 1

Related Questions