【问题标题】:KnockoutJS binding change event to two or more form propertyKnockoutJS 将更改事件绑定到两个或多个表单属性
【发布时间】:2013-07-22 17:18:53
【问题描述】:

我是 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,因为它非常优雅和干净。

【问题讨论】:

    标签: knockout.js


    【解决方案1】:

    好的,Knockout 已嵌入更改事件。只需使用 observables。

    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,因为我不知道你从哪里得到数据。无论如何,根据subscribe function 中的ID 获取type,对type 执行与ID 相同的操作

    【讨论】:

    • 我尝试订阅该属性,但它给了我太多递归错误。很抱歉,如果我没有完全编写代码,我已经为您添加了更多细节
    【解决方案2】:

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

    了解下拉列表中没有绑定 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
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-12-06
      • 1970-01-01
      • 2016-02-25
      • 1970-01-01
      • 1970-01-01
      • 2013-01-27
      • 1970-01-01
      相关资源
      最近更新 更多