javascript - knockout - 如何订阅多个下拉菜单(选择)并绑定(bind)到模型

标签 javascript html knockout.js drop-down-menu knockout-3.0

SO 爱好者和 javascript 开发人员,

如何将多个下拉列表绑定(bind)到一个模型并为每个下拉列表分别订阅其更改事件?

我有一个基本的形式。你可以在 jsFiddle 中看到它:http://jsfiddle.net/2Mnr3/7/
为什么当我选择一个时,所有选择的字段都会一起改变?我怎样才能以单独的方式做到这一点?

这是我的 HTML:

<div class='liveExample'> 

<h2>Orders</h2>
<div id='contactsList'>
    <table class='contactsEditor'>
        <tr>
            <th>First Name</th>
            <th>Last Name</th>
            <th>Service</th>
        </tr>
        <tbody data-bind="foreach: contacts">
            <tr>
                <td>
                    <input data-bind='value: firstName' />
                    <div><a href='#' data-bind='click: $root.removeContact'>Delete</a></div>
                </td>
                <td><input data-bind='value: lastName' /></td>
                <td>
                    <table>
                        <tbody data-bind="foreach: services">
                            <tr>

                                <td>

                                    <select data-bind='options: catalog, value: $root.selectedId, optionsText: "name", optionsCaption: "Select..."'> </select>
                                </td>

                                <td>
                                    <div data-bind="visible: $root.selectedId()">
                                        <span data-bind='text: $root.selectedId.price'> </span>
                                        <!--<span data-bind='text: "asd"'> </span>-->
                                    </div>
                                <td>

                                <a href='#' data-bind='click: $root.removeService'>Delete</a></td>
                            </tr>
                        </tbody>
                    </table>
                    <a href='#' data-bind='click: $root.addService'>Add service</a>
                </td>
            </tr>
        </tbody>
    </table>
</div>

<p>
    <button data-bind='click: addContact'>Add customer </button>
    <button data-bind='click: save, enable: contacts().length > 0'>JSON</button>
</p>

<textarea data-bind='value: lastSavedJson' rows='5' cols='60' disabled
          ='disabled'> </textarea>

以及带有 Knockout 库的 Javascript 代码:

function formatCurrency(value) {
    console.log(value);
    return value;
}

var serviceTypes = [
        { name: "Service One", id: "1", price: "10 USD"},
        { name: "Service Two", id: "2", price: "9 USD"},
        { name: "Service Three", id: "3", price: "25 USD"},
        { name: "Service Four", id: "4", price: "42 USD"}
      ];

var initialData = [
{ firstName: "John", lastName: "Carter", services: [{ catalog: serviceTypes, id: 0 }, { catalog: serviceTypes, id: 2 }]
}
];

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


self.serviceTypes = ko.observableArray(serviceTypes);
self.selectedId = ko.observable('1');

self.selectedId.subscribe(function(item){
    return ko.utils.arrayFirst(serviceTypes, function(service) {
        return service;
    });
});

self.addContact = function() {
    self.contacts.push({
        firstName: "",
        lastName: "",
        services: ko.observableArray([
            {
                catalog: this.serviceTypes,
            }])
    });
};

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


self.addService = function(contact) {
    contact.services.push({
        catalog: self.serviceTypes,
    });
};

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

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

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

ko.applyBindings(new ContactsModel(initialData));

最佳答案

您正在共享相同的 observable($root.selectedId) 而不是每个目录都应该有自己的 selectedId 副本。为此,您可以使用构造函数,例如,

function Catalog(serviceTypes, d) {
   this.catalog = serviceTypes;
   this.selectedId = ko.observable(d || null);
   this.selectedId.subscribe(function (item) {
     //Subscriber Handler
   });
}
var initialData = [{
  firstName: "John",
  lastName: "Carter",
  services: [new Catalog(serviceTypes, 1), new Catalog(serviceTypes, 2)]
}];

addContact 和 addService 函数也发生了变化。

 self.addContact = function () {
    self.contacts.push({
        firstName: "",
        lastName: "",
        services: ko.observableArray([new Catalog(serviceTypes)])
    });
 };

 self.addService = function (contact) {
    contact.services.push(new Catalog(serviceTypes));
 };

Fiddle Demo

关于javascript - knockout - 如何订阅多个下拉菜单(选择)并绑定(bind)到模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24302933/

相关文章:

javascript - iframe 中的表单发布将父级重定向到发布 URL

javascript - 在 MongoDb 中使用 mapReduce 获取文档(行)计数

javascript - 使用jquery查找元素的属性

html - Twitter Bootstrap - 居中内容

javascript - 短父元素中 float 图像上不需要的底部边距

javascript - 从 javascript 将 Click 事件放置在 html 中的 anchor 标记上?

javascript - 使用 javascript 从 Knockout.Js 读取 Json 数据

javascript - 从变量对象中删除 DOM 元素以将其发布到服务器

javascript - 如何使 bootstrap-datetimepicker 在 Firefox 上与 knockout 一起使用

javascript - 仅订阅新条目或已删除条目的可观察数组