Search code examples
jqueryruby-on-railsruby-on-rails-3.1ujs

$.validator.unobtrusive.parse - jquery in rails


I found this question and answer that talks about $.validator.unobtrusive.parse

jquery ujs not functioning when I remotely load partials/content with remote calls or jQuery

It looks like this is what I need to do to make jquery work on parts of a page that have been loaded using ajax.

But I would like to know what it's doing! Is it calling rails ujs, or is it talking to jquery directly? I've searched both the rails ujs git hub site and the jquery docs and couldn't see anything in either of those places. Is there any documentation anywhere?

Thanks for any help.


Perhaps this is clearer:

When I've added or changed part of the page using create.js.erb or update.js.erb how do I get jquery to work on these parts of the page. I'm trying to make elements sortable again, this question is about best-in-place editing, there are several other questions out there and the above link seems to be the only answer, and I can't make that work.

So how do you get jquery to "look at" parts of your page you've already changed once using rails ujs.


Solution

  • This is very dependent on the kind of page element you are dealing with that you want to 're-work', and how the original 'work' was triggered.

    If the original jquery code get's trigger simply via:

    $(document).ready(function(){
      $('#mydiv").css('color','red');
    });
    

    And you want to reset the div's color after update.js.erb changes it's contents (I know, dumb example), you could create a custom event and bind it to the div:

    $(document).ready(function(){
      $('#mydiv").on('rework', function() {
        $(this).css('color','red');
      });
    });
    

    Then, on the last line of update.js.erb you could do this:

    $('#mydiv').trigger('rework');
    

    If the original work were fired off via an on change event, or a click event, etc. Then you could just trigger that event:

    $('#mydiv').trigger('click');
    

    Triggering events is trick, because a triggered event is NOT exactly the same as the actual event, and events are tricky in general.

    It may be as simple as just slapping duplicate code at the end of your update.js.erb, if it's a simple one liner or a few lines.