I have an RJS problem. I'm trying to write a helper method that
replaces a given div element with a given partial, if and only if that
div exists. I can do this with something like:
The problem with this (apart from it being ugly code) is that the
partial my_partial is rendered even if the div element my_div doesn't
exist. In my app, some of the partials I want to use here are pretty
complex, and rendering them unnecessarily causes a pretty serious
slowdown. Does anyone know of a way to solve this problem?
Thanks Fred, that is a good point! There's a lot of places that I want
to do this, so I'd want to automate the process of specifying what
elements are present. Perhaps it would be possible to use an
Ajax.Responder method to collect a list of divs that are present on
the page and send it with each Ajax request? I'm not really sure how
to do this, and how to access the JS variables from Rails (as it's the
RJS script which I want to prevent from rendering templates). I may be
overcomplicating the issue... any thoughts?
Thanks Fred, that is a good point! There's a lot of places that I want
to do this, so I'd want to automate the process of specifying what
elements are present. Perhaps it would be possible to use an
Ajax.Responder method to collect a list of divs that are present on
the page and send it with each Ajax request? I'm not really sure how
to do this, and how to access the JS variables from Rails (as it's the
RJS script which I want to prevent from rendering templates). I may be
overcomplicating the issue... any thoughts?
The with option to the various remote helpers might be useful, so
link_to_remote 'Foo', :url => {...}, :with => "{foo: foo, bar: bar}"
will submit the javascript parameters foo and bar. You can of course
have pretty much any javascript in there.
Collecting all the divs on the page would probably be over the top
though, i'd trip it down to
link_to_remote 'Foo', :url => {...}, :with => "{needsRefresh: !$
('foo')}", so needsRefresh will be false if $('foo') exists
Interestingly, when I used the syntax you suggested ("{needsRefresh: !$
('foo')}"), the needsRefresh variable wasn't available to the RJS
script, at least not in the params hash. Instead I pieced together a
string argument of the form "'foo='+$('foo')+'&bar='+$('bar')" and
passed this to the :with option. This was then available in the params
hash.