View模型在Knockout中无法更新

时间:2015-06-24 17:46:55

标签: knockout.js

我熟悉React,而不熟悉Knockout。我预计,一旦我为一个观察者分配了一个值,它就会立即反映出来......但由于某种原因,这种情况并没有发生。

<span data-bind="text: myMessage"></span>

 <script>
        var viewModel;

        $.ajax({
            url: "/api/document/",
            dataType: "json",
            method: "GET"
        }).done(function (data) {
            viewModel = {
                myMessage: ko.observable()
            };

            viewModel.myMessage(data[0].Name);
        }).fail(function() {
            alert("something totally awful just happened.");
        });

    </script>

这个ajax调用返回一个文本字符串,我已经确认它正常工作。是否有原因在页面上没有显示跨度?

2 个答案:

答案 0 :(得分:2)

您需要创建一次视图模型,将其应用于DOM并在AJAX调用中更新它:

<span data-bind="text: myMessage"></span>

 <script>
        var viewModel =  {
            myMessage: ko.observable()
        };
        ko.applyBindings(viewModel);

        $.ajax({
            url: "/api/document/",
            dataType: "json",
            method: "GET"
        }).done(function (data) {
            viewModel.myMessage(data[0].Name);
        }).fail(function() {
            alert("something totally awful just happened.");
        });

    </script>

答案 1 :(得分:-1)

您错过了ko.applyBindings(viewModel);

<span data-bind="text: myMessage"></span>

<script>
    var viewModel;

    $.ajax({
        url: "/api/document/",
        dataType: "json",
        method: "GET"
    }).done(function (data) {
        viewModel = {
            myMessage: ko.observable()
        };

        viewModel.myMessage(data[0].Name);
        ko.applyBindings(viewModel);
    }).fail(function() {
        alert("something totally awful just happened.");
    });

</script>