条件视图模型绑定

时间:2013-04-17 14:55:57

标签: mvvm knockout.js

您好我已经开始使用Knockout了,因为它的目的比jQuery更容易。我之前使用过jQuery,但这使我的代码几乎不可读。

我有这个javascript viewmodel

function ovm() {
    this.delStreet = ko.observable("");
    this.deliveryNotSameAsInvoice = ko.observable(false);
    this.invStreet = ko.observable("");
}
ko.applyBindings(new ovm());

和这个HTML:

<label><input type="checkbox" data-bind="checked: deliveryNotSameAsInvoice" />if your invoice address is not the same as delivery</label>
<div id="delivery">
    <input type="text" placeholder="Street" 
        data-bind="value: delStreet, valueUpdate:'afterkeydown'" />
</div>
<div id="invoice" data-bind="visible: deliveryNotSameAsInvoice">
    <input type="text" placeholder="Street" 
        data-bind="value: invStreet, valueUpdate:'afterkeydown'" />
</div>
<hr/>
Delivery street: <span data-bind="text: delStreet"></span><br/>
Invoice street: <span data-bind="text: invStreet"></span><br/>

问题是我希望invStreet具有delStreet的值,只要取消选中该复选框即可。我有working jsFiddle here 并找到了这个SO question about conditional binding 但我找不到一个好的代码示例。在jquery中,我必须将keyup事件绑定到每个文本框,并且取决于是否选中了复选框,我必须设置几个字段。这是很多工作。特别是对于更大的“视图模型”

1 个答案:

答案 0 :(得分:1)

使用invStreet的计算observable ..像这样

function ovm() {
     var self = this;
     this.delStreet = ko.observable("");
     this.deliveryNotSameAsInvoice = ko.observable(false);
     this.invStreet = ko.observable("");
     var invStreetCheck = ko.computed(function(){
         var checked = self.deliveryNotSameAsInvoice(),
             delStreet = self.delStreet();
         if(!checked)
             return self.invStreet(delStreet);
         return self.invStreet();
     });
 }

 ko.applyBindings(new ovm());

现在当检查的绑定为true时,它将返回“”否则它将包含delStreet。值。