当observableArray在Knockout中只有一个项时,如何禁用按钮

时间:2014-02-10 07:49:57

标签: knockout.js

如果只有一个电话号码记录,如何禁用Remove按钮;如果只有一个联系人,则如果Delete按钮禁用。

检查jsfiddle http://jsfiddle.net/3Ajnj/17/

这是我的标记:

<div data-bind="foreach: contacts">
    <span data-bind="text: firstName"></span>
    <span data-bind="text: lastName"></span>
    <div data-bind="foreach: phones">
        <span data-bind="text: type"></span>
        <span data-bind="text: number"></span>
        <button data-bind="click: removePhone">Remove</button><br/>
    </div>
</div>

这是我的ViewModel:

var initialData = [
    { firstName: "Danny", lastName: "LaRusso", phones: [
        { type: "Mobile", number: "(555) 121-2121" },
        { type: "Home", number: "(555) 123-4567"}]
    },
    { firstName: "Sensei", lastName: "Miyagi", phones: [
        { type: "Mobile", number: "(555) 444-2222" },
        { type: "Home", number: "(555) 999-1212"}]
    } ];   var ContactsModel = function(contacts) {

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


self.addContact = function() {
    self.contacts.push({
        firstName: "",
        lastName: "",
        phones: ko.observableArray()
    });
};

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

self.addPhone = function(contact) {
    contact.phones.push({
        type: "",
        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));

1 个答案:

答案 0 :(得分:4)

data-bind中,您可以执行以下操作以禁用联系人删除按钮:

enable: $parent.contacts().length > 1

以下禁用手机删除按钮:

enable: $parent.phones().length > 1

完整加价:

<div data-bind="foreach: contacts">
    <span data-bind="text: firstName"></span>
    <span data-bind="text: lastName"></span>
    <button data-bind="click: $root.removeContact, 
            enable: $parent.contacts().length > 1">Delete</button>
    <div data-bind="foreach: phones">
        <span data-bind="text: type"></span>
        <span data-bind="text: number"></span>
        <button data-bind="click: $root.removePhone, 
                enable: $parent.phones().length > 1">Remove</button>
        <br/>        
    </div>    
</div>

这是一个新的小提琴,你需要的功能包括:

JSFiddle http://jsfiddle.net/3Ajnj/19/