0

我是 KnockoutJS 的新手,所以请原谅我的新手问题。

我有一个自定义 UI 控件(下拉菜单),其中包含两个更新两个表单属性的值。第一个属性是“ID”,第二个是“类型”。

Example of Drop-down values:
("ID", "Type") *each drop-down options has two property, ID and Type*
("A1", "Car")
("B3", "Bike")

以我的形式

<form id="abc-form" data-bind="event: { change: save }">
    <input type="hidden" name="ID" value="" data-bind="value: ID"/>
    <input type="hidden" name="Type" value="" data-bind="value: Type"/>
</form>

我制作了控件,这样如果用户单击其中一个选项。它将更新隐藏的输入,并触发更改事件,因此 KnockoutJS 将调用保存函数向服务器发送保存请求。

如果我只有“ID”或“类型”,我无法保存。我需要一对“ID”和“Type”。

如果我使用它来检测单个属性的更改,我的事件绑定可以正常工作。但是我不能使用 KnockoutJS 同时更新两个属性。我一直只填写“ID”属性。

$("input#ID").val("A1")
$("input#Type").val("Car")
$("input#ID").trigger("change")

我尝试了很多组合,但似乎 KnockoutJS 只更改了我用 change 事件触发的属性,在上面的示例中,它只会填充 ID 属性。

有没有办法使用 KnockoutJS 填充两个属性并发送保存请求?

我真的很喜欢 KnockoutJS,因为它非常优雅和干净。

4

2 回答 2

1

好的,Knockout 已经嵌入了更改事件。只需使用可观察对象。

var selected = ko.observable();

然后在select

<select data-bind="value: selected">

然后,订阅更改

var id = ko.observable();
selected.subscribe(function(newval){
    // newval is the ID
    id(newval);
});

从这里开始,根据您在订阅功能中获得的 ID,再次预填充隐藏的输入字段,最好也使用上面和下面的示例中的 observables

<input type="hidden" name="ID" data-bind="value: id" />

我漏掉了,type因为我不知道你从哪里得到数据。无论如何,type基于ID中的subscribe function,并与 withtype一样做ID

于 2013-07-22T08:43:11.273 回答
1

您可以将两个输入绑定到 VM 中的某些属性。在虚拟机中,我们可以有一个selected与下拉列表绑定的属性,以及selectedType每次selected下拉列表更改时计算的属性。

重要的是要理解 Type 没有绑定在下拉列表中,因此我们应该通过查找items数组中具有相同 id 的项来查找类型。

看法:

<input type="hidden" name="ID"  data-bind="value: selected"/>
<input type="hidden" name="Type" data-bind="value: selectedType"/>
<select data-bind="options: items, value: selected, optionsText: 'type', optionsValue: 'id'">

虚拟机:

var items = ko.observableArray([{ id: 'A1' , type: 'Car'  },{ id: 'B3' , type: 'Bike'  } ]);
ver selected = ko.observable();
var selectedType = ko.observable();
selected.subscribe(function(id){
  var item = $.grep(items(), function(i){ return i.id == id; });
  selectedType(item.type);
  //Your form submission
});
于 2013-07-22T09:18:53.027 回答