Stimulus: preventDefault not stopping propagation with remote link_to

Created on 12 Jul 2018  路  3Comments  路  Source: hotwired/stimulus

Problem

Within a stimulus controller action, event.preventDefault is not stopping the ajax request created with remote: true from a link_to element

Expected

I would expect event.preventDefault to stop the ajax request as I believe it does with button_to etc.

Sample code

````erb

index.erb

<%= link_to 'New Article', new_article_path, remote: true, data: {action: "hello#testPreventDefault"} %>
````

js //hello_controller.js testPreventDefault(event){ event.preventDefault() }

Output

The logs show the new route is accessed even though event.preventDefault() is called:

screen shot 2018-07-12 at 7 25 59 pm

Sample repo

https://github.com/MrHubble/stimuluslinkto

Most helpful comment

event.preventDefault() only prevents the link from being followed. event.stopImmediatePropagation() will stop the event from being propagated to other event handlers.

All 3 comments

event.preventDefault() only prevents the link from being followed. event.stopImmediatePropagation() will stop the event from being propagated to other event handlers.

@fourcube thanks for taking the time to help.

With event.stopImmediatePropagation() the request still went through but this time as HTML rather than JS:

screen shot 2018-07-12 at 9 27 09 pm

@fourcube I think I must have misunderstood your answer. When I use both preventDefault() and stopImmediatePropagation() together it works which is what I think you were referring to. So the solution is

js testPreventDefault(event){ event.preventDefault() event.stopImmediatePropagation() }

Seems I have some reading to do. Thanks again.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

jenkijo picture jenkijo  路  3Comments

ngan picture ngan  路  3Comments

dwightwatson picture dwightwatson  路  3Comments

angarc picture angarc  路  3Comments

gerdriesselmann picture gerdriesselmann  路  3Comments