仅在系统修改时禁用输入

时间:2014-05-03 21:55:47

标签: javascript jquery knockout.js knockout-3.0

此代码执行搜索并显示结果。我想有条件地禁用input s。我正在使用knockout来控制input被禁用的时间。

要求:

    系统设置时,
  1. input被禁用。
  2. 不应禁用用户输入。
  3. 在以下代码中,来自readDatabase()的输入效果很好。如果用户键入Hometown / Nickname input,则标签输出input禁用。如何修复此代码以满足第二个要求?

    更新

    我不反对从jQuery获得一些帮助。我不想完全抛弃我的视图模型绑定。

    Fiddle

    HTML

    Name: <input type="text" data-bind="value: userInput, valueUpdate: 'input'" /><br />
    Hometown: <input type="text" data-bind="value: Hometown, disable: Hometown" /><br />
    NickName: <input type="text" data-bind="value: Address, disable: Address" />
    

    的JavaScript

     function MyViewModel() {
             var self = this;
             self.userInput = ko.observable();
             self.Hometown = ko.observable();
             self.Address = ko.observable();             
    
             self.userInput.subscribe(function () {
                 readDatabase(self);
             });
         }
         ko.applyBindings(new MyViewModel());
    
    function readDatabase(self){
        if(self.userInput().substring(0,1) == "a"){
            self.Hometown("A town");
            self.Address("A address");
        }
        else {
            self.Hometown("");
            self.Address("Other address");
        }
    }
    

1 个答案:

答案 0 :(得分:3)

您可以使用extender提供指示数据来源的标记:

ko.extenders.isServerSet = function (target, value) {
    target.isServerSet = ko.observable(value);
    return target;
};

function MyViewModel() {
    var self = this;
    self.userInput = ko.observable();
    self.Hometown = ko.observable().extend({
        isServerSet: false
    });;
    self.Address = ko.observable().extend({
        isServerSet: false
    });;
    self.userInput.subscribe(function () {
        readDatabase(self);
    });
}
ko.applyBindings(new MyViewModel());

function readDatabase(self) {
    if (self.userInput().substring(0, 1) == "a") {
        // don't overwrite user-provided values
        if (!self.Hometown()) {
            self.Hometown("A town");
            self.Hometown.isServerSet(true);
        }
        if (!self.Address()) {
            self.Address("A address");
            self.Address.isServerSet(true);
        }
    } else {
        self.Hometown("");
        self.Address("Other address");
    }
}
Name: <input type="text" data-bind="value: userInput, valueUpdate: 'input'" /><br />
Hometown: <input type="text" data-bind="value: Hometown, disable: Hometown.isServerSet" /><br />
NickName: <input type="text" data-bind="value: Address, disable: Address.isServerSet" />

Updated fiddle