export default class extends Controller {
static targets = [ "visible", "map" ]
mapTargetConnected(element) {
this.name = "aaa"
}
add(event) {
console.log(this.name) // this will be undefined in the browser log
}
}
here is the HTML code
<%= form_with(model: @location, local: false, url: location_path(), data: {controller: 'location', action: 'ajax:beforeSend->location#add'}) do |form| %>
....
<% end %>
this is the code regarding form submit via ajax request. if i access the this.name variable inside the add method or click event its says the variable is undefined… but if i same name variable assign it in connect() method than it’s working…
but i want to assign variable at targetConnected method and use it in the add action method.
A solution is to create another small controller dedicated to the target element, when it get connected then it emit a window event. The main location controller listen this event…
thanks for the reply… But problem is there is i want to set the variable in the connectedTarget method. is that limitation to not assign variable like this? i want to understand this? sorry if i asked to much questions
Problem is in this above code i’m going to use the map, and map is load from the another file. basically i want to load map in the connectedTarget method and then use map in the click add event? hope you got my point
Thank you @tleish for the reply…i found the issue that issue is regarding the turbolinks… so basically its called mapTargetConnected method twice due to turbolinks… mapTargetConnected connected twice without called mapTargetDisconnected method.
With turbo, you have a preview of the page when you back to it. During the preview, it load the page and replace what it have to replace.
In a stimulus controller, you can check if document.documentElement.hasAttribute(“data-turbo-preview”)) to know it and prevent, sometime, to get method called twice.
mapTargetConnected() {
if (document.documentElement.hasAttribute("data-turbo-preview")) return
// do what you want
}