单击按钮时映射在淘汰赛中不起作用

Mapping not working in knockout with the button click

点击按钮后映射无法正常工作,

我在敲除中使用了映射,但在单击按钮时更改输入文本值时未正确更改。 单击 加载用户数据 按钮

后需要更改 name 输入文本 的值

这是我的代码,

    <div class='sample'>
    <p>Load: <input type="button" value="Load User Data" data-bind="click: loadUserData" /></p>
    <p>Name: <input data-bind='value: firstName' /></p>
    <p>Save: <input type="button" value="Save User Data" data-bind="click: saveUserData" /></p>
</div>
<script>
    $(document).ready(function () {
        var viewModel = {};
        viewModel.firstName = 'Knockout JS';
        viewModel.loadUserData = function () {
            $.getJSON("/data.json", function (data) {
                // update the data in existing ViewModel.
                viewModel.firstName = data.name;
                ko.mapping.fromJS(data, viewModel);

            });
        };
        viewModel.saveUserData = function () {
            // Convert the viewModel into JSON.
            var data_to_send = { userData: ko.toJSON(viewModel) };
            // Send that JOSN data to server.
            $.post("WebService.asmx/updateData", data_to_send, function (data) {
                alert("Your data has been posted to the server!");
            });
        };
        ko.applyBindings(viewModel);
    });
</script>

我有什么问题吗?

为了使其更新 UI,您需要将 firstName 设为 observable

然后当你想修改一个可观察值时,你需要将其视为一个函数并将新值作为参数传递,如下所示firstName('newValue')

请参阅 link here 以获取更多信息和下面的示例:

var masterVM = (function () {
  var self = this;      
  self.firstName = ko.observable("Knockout JS");
  self.loadUserData = function() {
    var currentName = self.firstName();
    self.firstName(currentName + "Updated");
  }
})();

ko.applyBindings(masterVM); 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>

<p>Load: <input type="button" value="Load User Data" data-bind="click: loadUserData" /></p>
<p>Name: <input data-bind='value: firstName' /></p>