禁用在Knockout中无法正常工作

时间:2015-03-31 09:13:43

标签: javascript knockout.js

如果字段已被删除,我需要禁用字段,但它无法正常工作。

我创建了一个JSFiddle:https://jsfiddle.net/mdawood1991/fs1exz6q/

x标记应删除项目(禁用TextBox),但不是:

这是我的ViewModel:

var viewModel = {};

function QuoteViewModel() {
    var self = this;
    self.Quantity = ko.observable();
    self.Price = ko.observable();
    self.Total = ko.computed(function () {
        return this.Price() * this.Quantity();
    }, this);
    self.isDeleted = ko.observable(false);


    self.remove = function (item) {
        console.log('A');
        item.isDeleted = ko.observable(true);
        console.log(item.isDeleted());
    }
};

viewModel = new QuoteViewModel();
ko.applyBindings(viewModel);

这是相关的HTML:

<div class="col-md-3">
    <div class="form-group">
        <label class="control-label">Price Type</label>
    </div>
</div>
<div class="col-md-3">
    <div class="form-group">
        <label class="control-label">Quantity</label>
        <input type="text" class="form-control" data-bind="numeric: Quantity, value: Quantity, valueUpdate: 'afterkeydown', disable: !isDeleted()" />
        <!--numeric: number, value: number, valueUpdate: 'afterkeydown'-->
    </div>
</div>
<div class="col-md-3">
    <div class="form-group">
        <label class="control-label">Price</label>
        <div class="input-group">
            <div class="input-group-addon">$</div>
            <input type="text" class="form-control" data-bind="numeric: Price, value: Price, valueUpdate: 'afterkeydown'" />
        </div>
    </div>
</div>
<div class="col-md-2">
    <div class="form-group">
        <label class="control-label">Total</label>
        <div class="input-group">
            <div class="input-group-addon">$</div>
            <input type="text" class="form-control" data-bind="textInput: Total" />
        </div>
    </div>
</div>
<div class="col-md-1"> <span class="glyphicon glyphicon-remove" data-bind="click: remove"></span>

</div>
<pre data-bind="text: ko.toJSON($data, null, 2)"></pre>

当我点击'x'时,它会将isDeleted属性更新为TRUE,但不会在我的HTML(<pre> <p>)标记中更新。

它应该如何运作:

 1. When isDeleted == true (Disable fields) 
 2. When isDeleted == false (Enable)

1 个答案:

答案 0 :(得分:2)

Setting an observable goes by invoking it as a function。而不是:

item.isDeleted = ko.observable(true);

使用:

item.isDeleted(true);

请参阅this fiddle了解演示。