Reputation: 1004
I've been trying to write an equivalent for the following in cljs using the Domina library:
HTML:
<form id="my-form">
<input type="text />
<input type="submit" />
</form>
Javascript (jQuery):
$("#my-form").submit(function() {
console.log("submit suppressed");
return false;
});
A solution not to my satisfaction (without Domina library which is very verbose):
(set! (.-onsubmit (.getElementById js/document "my-form")) #(do
(.log js/console "submit suppressed")
false))
I've tried many solutions which all failed - all somewhat similar to:
(listen! (by-id "my-form") :submit #(do
(log "submit suppressed")
false))
It is on purpose that I don't use the click event, because I also want the function to be executed when the form is submitted by code or keyboard.
Upvotes: 2
Views: 1460
Reputation: 2727
When you return false
from within a jQuery
event handler, the library will automatically call e.preventDefault
and e.stopPropagation
(for more info see here). Calling this functions is the right way to control the behaviour of the event
.
Domina wraps js/Event
in something that ClojureScript
understands. So you can call preventDefault
and stopPropagation
directly, without using the Javascript interop. You can read more about this neat trick here: https://github.com/levand/domina#event-objects.
This trick is probably what is causing returning false
to not work at all. The way this trick is implemented (take a look at the code here) is by wrapping your function with another function that always return true
.
So your code should be more like this:
(listen! (by-id "my-form") :submit
(fn [e]
(do
(log "submit suppressed")
(prevent-default e)
(stop-propagation e))))
Upvotes: 3