jquery mobile and knockout form submit binding

2019-01-24 18:27发布

问题:

I stumbled on an apparent incompatibility between knockoutjs and jquery mobile when it comes to form submit behavior.

Consider the following markup:

<form data-bind="submit: myKoSubmitAction">
   <!-- form fields here -->
</form>

The intention is that knockout prevents server post/get and instead calls myKoSubmitAction. jqm will also prevent standard submit behavior only for jqm the reason is that the form submit is replaced by an ajax request.

So while knockout (presumably) succeeds at preventing the standard server request, it fails to prevent jqm from sending an ajax request.

I found the answer to this problem in a google group and thought it should be on SO as well. See below

回答1:

You can also add data-ajax="false" to the <form> element.

See Submitting Forms.



回答2:

The best solution I have been able to find is the following custom ko binding:

//This binding fixes apparent incompatibility between knockout and jqm
ko.bindingHandlers.jqmsubmit = {
  init: function (el, accessor, allbindings, vm) {
    ko.bindingHandlers.submit.init(el, accessor, allbindings, vm);
    $(el).submit(function (e) {
        // prevent the submit behavior
        e.preventDefault();
        e.stopPropagation();
        return false;
    });
  }
};

To be used in the place of the standard submit ko binding:

<form data-bind="jqmsubmit: myKoSubmitAction">
  <!-- form fields here -->
</form>