2014-02-05 101 views
0

當我有輸入和按鈕時,我有頁面。覆蓋輸入時更新值按

<div> 
    <div class="input-group"> 
     <span class="input-group-addon">Enter test</span> 
     <input type="Text" class="form-control" data-bind="value:Test, event: { keypress: searchKeyboardCmd}" required /> 
    </div> 
</div> 
<button data-bind=' event:{click:foo}' class="btn btn-default">Submit</button> 

和我的代碼:

var ViewModel = function() { 
    var self = this; 
    self.Test = ko.observable(); 
    self.data = ko.observableArray([]); 
    self.DeviceId = ko.observable(); 
    self.number = ko.observable(1); 
    self.MeUser = ko.observable(true); 
    self.searchKeyboardCmd = function (data, event) { 
     if (event.keyCode == 13) 
      alert("Znalazlem enter " + ko.toJSON(self)); 
     return true; 
    }; 
    self.foo = function() { 
     alert("foo"); 
    }   
}; 
ko.applyBindings(new ViewModel()); 

});

我的代碼有問題。我用這個代碼捕獲輸入:

 self.searchKeyboardCmd = function (data, event) { 
     if (event.keyCode == 13) 
      alert("Znalazlem enter " + ko.toJSON(self)); 
     return true; 
    }; 

它完美地捕獲,但綁定的對象在調用alert後更新。所以在第一次輸入值爲Test時爲null。第二次輸入後,我有第一個值,等等。任何人都可以建議我如何修改此代碼?

回答

1

的問題是,該事件是blur事件之前執行(也就是當值更新您可以通過添加valueupdate: 'afterkeydown'到輸入確保更新被每一次擊鍵後更新:

<div> 
    <div class="input-group"> 
     <span class="input-group-addon">Enter test</span> 
     <input type="Text" class="form-control" 
       data-bind="valueUpdate: 'afterkeydown', value:Test, event: { keypress: searchKeyboardCmd}" required /> 
    </div> 
</div> 
<button data-bind=' event:{click:foo}' class="btn btn-default">Submit</button>