سؤال

This code does a search and displays the results. I want to conditionally disable inputs.I am using knockout to control when an input is disabled.

Requirement:

  1. input is disabled when set by the system.
  2. User input should not be disabled.

In the following code input that comes from readDatabase() works well. If the user types in the Hometown/Nickname inputthen tabs out then input disables. How can I fix this code to meet the second requirment?

Update

I am not opposed to getting some help from jQuery. I do not want to throw out my view model binding entirely.

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");
    }
}
هل كانت مفيدة؟

المحلول

You could use an extender to provide a flag indicating where the data came from:

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

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top