Knockout Mutliple Dropdown可添加新物品

时间:2016-10-10 19:49:59

标签: javascript html mvvm knockout.js

我是否有可能有多个具有项目的下拉菜单(不是特定数量)和一个将新项目添加到下拉列表的新项目选项。

例如,将有~5个下拉菜单,用户选择项目编号。当他们选择New Item时,它会将一个Item添加到列表中

这是我得到它,不知道我怎么能用淘汰赛处理这个问题。它真的可能吗?

<select data-bind="options: items, optionsText: 'name', optionsValue: 'id', value: selectedChoice"></select>
<br/>
<select data-bind="options: items, optionsText: 'name', optionsValue: 'id', value: selectedChoice"></select>
<br/>
<select data-bind="options: items, optionsText: 'name', optionsValue: 'id', value: selectedChoice"></select>
<br/>


var Item = function(data){
var self = this;
self.id = ko.observable(data.id);
self.name = ko.observable(data.name);
};
var viewModel = function(data) {
   var self = this;
   self.selectedChoice = ko.observable();
   self.items = ko.observableArray([
        new Item({id: "1", name: "Item 1"}),
        new Item({id: "2", name: "Item 2"}),
        new Item({id: "3", name: "New Item"})]);
    self.sendMe = function(){

        alert(ko.toJSON({ selectedItemId: this.selectedChoice()}));
    };
};

ko.applyBindings(new viewModel());

https://jsfiddle.net/dqUAz/1470/

1 个答案:

答案 0 :(得分:0)

实现此目的的一种方法是订阅 selectedChoice observable并随时更新数组&#39; New Item&#39;被选中:

self.selectedChoice.subscribe(function(newValue) {
    var lastItem = self.items()[self.items().length - 1];
    if (newValue === lastItem.id()) {
        // Add the new item
        var id = self.items().length + 1;
        var name = 'Item ' + self.items().length;
        var item = new Item({id: id, name: name});
        self.items.push(item);

        // Drop and re-add the 'New Item' item so that it remains at the bottom
        self.items.remove(lastItem);
        self.items.push(lastItem);

        // Select the newly added item
        self.selectedChoice(id);
    }
});

小提琴: https://jsfiddle.net/dw1284/60n7078s/2/