根据模型删除值Binding

时间:2014-06-18 12:13:10

标签: knockout.js

我有一个模型属性,有时应绑定到input元素,有时绑定到select元素,该元素基于配置。
我在两个元素上使用值绑定,并使用可见绑定隐藏任一个。

由于两个绑定都在页面上,当input可见时,当我输入隐藏select中不存在的某些文本时,我无法更改其值。因此,如果input元素可见(isDropdown为false),我不希望绑定select(还是有其他更好的方法来处理它?)。

示例Javascript模型

var player = function (name, age, country, isDropdown) {
    this.name = ko.observable(name);
    this.age = ko.observable(age);
    this.country = ko.observable(country);
    this.isDropdown = ko.observable(isDropdown);
};

var playerModel = function () {
    var self = this;
    self.myPlayer = new player('Murray', 28, 'UK', false);
    //self.myPlayer = new player('Murray', 28, 'UK', true);
    self.countryList = ['US', 'UK', 'SWISS'];   
}
var model = new playerModel();
ko.applyBindings(model);

HTML代码

    Name:
<input type="text" data-bind="value: myPlayer.name" />
<br/>Age:
<input type="text" data-bind="value: myPlayer.age" />
<br/>Country:
<input type="text" data-bind="value: myPlayer.country, visible: !(myPlayer.isDropdown())" />
<select data-bind="options: $root.countryList, 
    value:myPlayer.country, 
    optionsCaption:'Choose..',        
    visible: myPlayer.isDropdown()"></select>
<br/>
(There is a dropdown / input which is hidden, please swap the commented lines in javascript model to enable that )

各个JS小提琴是here

1 个答案:

答案 0 :(得分:1)

使用虚拟if绑定。这可以防止数据绑定选择元素在isDropdownfalse时位于DOM中并绑定。

<!-- ko ifnot: myPlayer.isDropdown -->
    <input type="text" data-bind="value: myPlayer.country" />
<!-- /ko -->
<!-- ko if: myPlayer.isDropdown -->
    <select data-bind="options: $root.countryList, 
        value:myPlayer.country, 
        optionsCaption:'Choose..'">
    </select>
<!-- /ko -->

JSFiddle