2

What's the right place to put javascript/coffeescript in Rails when working with partial being loaded via AJAX?

I would like to call:

$('.selector').datapicker() 

every time '_form' partial is loaded.

I can put this directly into the _form.html.erb partial and it would work like expected but I kinda feel like it's a wrong holder for js.

2 Answers 2

3

The 'right place' should be within the assets folder where all js scripts reside.

You can use:

$( document ).ajaxComplete(function( event,request, settings ) {
    $('.selector').datapicker();
});
Sign up to request clarification or add additional context in comments.

3 Comments

I don't think that I should trigger that js on every AJAX call
Trigger it on your ajax call complete function then: $.ajax({ url: "your_url" }).done(function() { $('.selector').datapicker(); });
sorry, but explicitly determining js to run per URL doesn't sound like a good idea
0

If you're using UJS data-remote to do the ajax, you can hook on to the ajax event that UJS makes. See here: https://github.com/rails/jquery-ujs/wiki/ajax

use ajax:complete to re-add datapicker to the element eg:

$('#submitted_form').on('ajax:complete', function(event, xhr, settings) {
  $('#date_field').datapicker();
});

...and then this would go in your assets/javascript folder.

Also check out this article: http://www.alfajango.com/blog/rails-3-remote-links-and-forms/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.