Hello,
We are developing our project fully in LiveView and are very excited about possibilities it provides. There are a couple of places in our code where we need to use JavaScript hooks (e.g. for autocomplete fields). However, while using those we encountered some behaviour of the updated
hook we didn’t expect.
We want to be able to bind a hook to a dom element and expect it to be triggered only if a assigns value for that element changes (@selected_tab
here). Here is the code:
<div phx-hook="initTabHooksGeocoder" data-selected-tabs="<%=@selected_tab %>" id="geocode-isolated"></div>
<div id="content">
<div class="date-initiator-checker autocomplete-initiator-checker" id="observe" phx-hook="datepickerShipmentCard">
<%= case @selected_tab do
"Segments" -> render(VoF.BOWeb.PartialsView, "segment_tab.html", assigns)
"Commission" -> render(VoF.BOWeb.PartialsView, "commission_tab.html")
end %>
</div>
</div>
As you can see, an element with a initTabHooksGeocoder
hook is isolated and has no children, whereas the element with an id content
renders segment_tab.html
template.
In the segment_tab.html
template there is the code the opens up a modal on click:
<button phx-click="open-modal">Split</button>
<div class="modal <%= if @open_modal do %> active<% end %>">
<%= render("split-segment-modal.html", assigns) %>
</div>
So if a @open_modal
variable is truthy, the modal will be opened. Here is the handle_event callback from our live component that will set that value:
def handle_event("open-modal", _, socket) do
{:noreply, assign(socket, :open_modal, true)}
end
Since the isolated div (the one with the initTabHooksGeocoder
hook) is in no way related (not a parent) to the html code that opens the modal, we expect that the updated
hook won’t be triggered when the modal is being opened. However, against our expectations, the following code will be executed and we will see the console.log in the console:
LiveHooks.initTabHooksGeocoder = {
updated(){
console.log('UPDATED dataset',this.el.dataset);
AutocompleteModule._init('.autocomplete', liveSocket, LiveHooks,'#form','.form-input-triggering-change', autoCompleteCheckers);
}
}
Any help is highly appreciated!