Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

JS event binding + Progressive render #33

Open
leoplct opened this issue Sep 9, 2019 · 1 comment
Open

JS event binding + Progressive render #33

leoplct opened this issue Sep 9, 2019 · 1 comment

Comments

@leoplct
Copy link

leoplct commented Sep 9, 2019

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
  })
@johnsonj
Copy link
Owner

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants