jQuery调用敲除方法

For some reason I want to call knockout method in jQuery.

Knockout viewModel is already binding. I don't know how to call it in jQuery.

Here is my code.

$(document).ready() {
  form_submit();
}

function form_submit() {
  var form = $('#form');
  var serializedData = form.serialize();
  $.get("{% url 'search:search' %}", serializedData, function(response) {
    AppViewModel.count(response.count); // I tried this, it says undefined is not a function
    //Then I tried:
    var newModel = new AppViewModel();
    newModel.count(response.count); //No errors, but UI doesn't change. I know it's because I'm not binding it. But I don't think I can binding it, because only 1 ko.binding allowed.
}

function AppViewModel() {
   var self = this;
   self.count = ko.observable(count); //Assume I initially assigned some value to count.
   //some other code below not related to this question.
}

ko.applyBindings(new AppViewModel());

Hope someone can help. Thanks!

Why don't you assign the result of calling new AppViewModel to a variable before applying the bindings on it? Then you can reference that variable inside your jQuery get callback.

Something like the following:

$(document).ready(function() {
    form_submit();
});

var vm = new AppViewModel();

function form_submit() {
    var form = $('#form');
    var serializedData = form.serialize();
    $.get("{% url 'search:search' %}", serializedData, function(response) {
        vm.count(response.count);
    });
}

function AppViewModel() {
   var self = this;
   this.count = ko.observable(count);
}


ko.applyBindings(vm);

You can also just bind to your form's submit event which should simplify some of your code organization.

For example, in the following HTML, I'm binding to my form's submit event:

<div id="myHTML">
    <form data-bind="submit: myFormHandler">
        <!-- form inputs here -->
    </form>
</div>

Then in my view model, I'd have the following:

function AppViewModel() {
    this.count = ko.observable();

    this.myFormHandler = function(formElement) {
        var self = this;
        var serializedData = $(formElement).serialize();
        $.get("{% url 'search:search' %}", serializedData, function(response) {
            self.count(response.count);
        });
    }
}

$(document).ready(function() {
    var vm = new AppViewModel();

    ko.applyBindings(vm, $("#myHTML")[0]);
});

Note that in the above example, I'm scoping my bindings to the myHTML div.