2017-08-30 77 views
0

我正在通過在表格單元格中輸入值更新數據到數據庫,如果驗證失敗,我需要將焦點設置在同一個單元格上。這張桌子是通過knockout.js視圖模型界定的。Knockout.js hasfocus

self.FirstName = ko.observable(report.OverallRetention).extend({ 
    reportValueChange: { 
    property: firstName 
    } 
}); 
ko.extenders.reportValueChange = function(target, option) { 
    debugger; 
    var _oldValue; 
    target.setFocus = function(val) { 
     target.hasfocus = val; 
    }; 
    target.subscribe(function(oldValue) { 
     _oldValue = oldValue; 
    }, null, 'beforeChange'); 
    target.subscribe(function(newValue) { ///////Want to set set focus here. 
+0

self.FirstName = ko.observable(報告.OverallRetention).extend({reportValueChange:{property:firstName}}); ko.extenders.reportValueChange = function(target,option){ debugger; var _oldValue; target.setFocus = function(val){ target.hasfocus = val; }; target.subscribe(function(oldValue){oldValue = oldValue; },null,'beforeChange'); target.subscribe(function(newValue){ ///////想在此處設置焦點 } – ALI

回答

0

難道你不只是使用hasFocus數據綁定?

https://jsfiddle.net/0o89pmju/52/

點擊清脆的名字按鈕,驗證將失敗。並且自動對焦將被設置爲名字。

我不太以下你的擴展,所以我用了一個需要從文檔http://knockoutjs.com/documentation/extenders.html

HTML

<p data-bind="css: { error: firstName.hasError }"> 
    <input data-bind='value: firstName, valueUpdate: "afterkeydown", hasFocus: firstName.hasError' /> 
    <span data-bind='visible: firstName.hasError, text: firstName.validationMessage'> </span> 
</p> 
<p data-bind="css: { error: lastName.hasError }"> 
    <input data-bind='value: lastName, valueUpdate: "afterkeydown"' /> 
    <span data-bind='visible: lastName.hasError, text: lastName.validationMessage'> </span> 
</p> 
<p> 
    <button data-bind="click: clearName">clear first name</button> 

    </button> 
</p> 

JS

ko.extenders.required = function(target, overrideMessage) { 
    //add some sub-observables to our observable 
    target.hasError = ko.observable(); 
    target.validationMessage = ko.observable(); 

    //define a function to do validation 
    function validate(newValue) { 
    target.hasError(newValue ? false : true); 
    target.validationMessage(newValue ? "" : overrideMessage || "This field is required"); 
    } 

    //initial validation 
    validate(target()); 

    //validate whenever the value changes 
    target.subscribe(validate); 

    //return the original observable 
    return target; 
}; 

function AppViewModel(first, last) { 
    var self = this; 
    this.firstName = ko.observable(first).extend({ 
    required: "Please enter a first name" 
    }); 
    this.lastName = ko.observable(last).extend({ 
    required: "" 
    }); 
    this.clearName = function() { 
    self.firstName(''); 
    self.lastName(''); 
    } 
} 

ko.applyBindings(new AppViewModel("Bob", "Smith")); 
+0

我已經使用了這種方法,但它在數據呈現中花費了太多時間。 – ALI