progressive_render icon indicating copy to clipboard operation
progressive_render copied to clipboard

JS event binding + Progressive render

Open leoplct opened this issue 6 years ago • 1 comments

This gem is fantastic! The only issue I have is to trigger a Jquery callback on a button click. This code below doesn't work because when the page is loaded Jquery doesn't found the "button.card" because it has not been loaded by progressive_render yet. How can I make it work?

 <%=progressive_render do %>
  <button class="card" />
<% end %>

$('.card').on('click', function(){
     THIS NEVER GET TRIGGERED
  })

leoplct avatar Sep 09 '19 20:09 leoplct

Hey @leoplct - thanks! (and sorry for the delay)

If you're writing this JavaScript in an asset that is loaded on page load (likely in rails!) then the jQuery code is binding on an object that doesn't yet exist. When you call $('.card') you're effectively returned a nil object that you're binding the event on, so it will never get fired. What you need to do is bind the event to an object that always exists, eg:

$(document).on('click', '.card', function() {
  // ...
})

Another option is to register the event handler when the content is added. The event progressive_render:end is raised for this purpose. For example:

$(document).on('progressive_render:end', function() {
  // ensure any handlers are registered
})

This is a common issue (see #29), we could use some docs about it.

johnsonj avatar Sep 17 '19 14:09 johnsonj