Knockout.js force change after JavaScript changes a textbox

烂漫一生 提交于 2020-01-03 04:38:10

问题


I have an input:

<input id="MyTextBox" type="text" data-bind="value: MyTextBox" />

If I change the textbox myself then data binding works... but if I set the text of the textbox with JQuery the textbox changes but no data bind occurs.

$("#MyTextBox").val("Some text");

How can I change a textbox without any keystrokes and still get binding to work?

Thank you


回答1:


When using Knockout, you generally shouldn't be using something else to modify the view. So instead of using jQuery to change the textbox value, use Knockout by modifying the observable it's bound to:

this.MyTextBox("Some text");

If you really need to modify the textbox outside of Knockout, you can signal the value binding by generating a change event:

$("#MyTextBox").val("Some text").change();



回答2:


When the change event was triggered will notify observer see the snippet, but i suggest to you use a custom bind handler to manipulate the directly DOM with KO;

You’re not limited to using the built-in bindings like click, value, and so on — you can create your own ones. This is how to control how observables interact with DOM elements, and gives you a lot of flexibility to encapsulate sophisticated behaviors in an easy-to-reuse way.

Ref. http://knockoutjs.com/documentation/custom-bindings.html

function viewModel(){
     this.val = ko.observable()
};

viewModel.prototype.changeValue= function(){
       $("#txt_data").val("Updated by JQuery: " + $("#txt_jqr").val()).change();      
};

ko.applyBindings(new viewModel());
label{
  margin-top:10px;
   display:block;
}
span{
    font-size: 1.4rem;
    font-weight: 700;
    margin-left: 20px;
    color: white;
    background-color: red;
    padding: 2px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<label for="txt_data">Data-Bind Text:</label>
<input type="text" id="txt_data" data-bind="value: val"/>
<span data-bind="text: val"></span>
<br/>
<label for="txt_jqr">Jquery Text to change:</label>
<input type="text" id="txt_jqr"/>
<br/>
<br/>
<button data-bind="click: changeValue">Change view model value</button>


来源:https://stackoverflow.com/questions/34100012/knockout-js-force-change-after-javascript-changes-a-textbox

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!