Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery mobile and knockout form submit binding

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

like image 610
LOAS Avatar asked Jan 16 '23 11:01

LOAS


2 Answers

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

See Submitting Forms.

like image 62
Mike White Avatar answered Jan 19 '23 02:01

Mike White


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>
like image 24
LOAS Avatar answered Jan 19 '23 00:01

LOAS