RJS: How to create an observer?

When updating a page with RJS is can happen that an element to which
observers are attached is exchanged with a new one. In my case, I have
an observed select element that gets replaced when some other input
element changes. When I replace the old select element with a new one,
the new select element doesn’t magically take over the observer(s)
attached to the old one, therefore I have to explicitly attach an
observer to the new one.

Surprisingly, there doesn’t seem to be a way to do this purely within
the confines of the JavaScriptGenerator. The best I’ve come up with is
to insert the necessary JavaScript code manually, i.e.

page << “new Form.Element.Observer(‘my_select_element’,” +
" function(element, value) { … });"

That doesn’t feel right. Is there no better way, either of doing it
without recourse to explicit JavaScript, or, better still, to keep
observers automatically attached to elements by id even after they have
been replaced.

Michael


Michael S.
mailto:[email protected]
http://www.schuerig.de/michael/

Michael S. wrote:

page << “new Form.Element.Observer(‘my_select_element’,” +
" function(element, value) { … });"

That doesn’t feel right. Is there no better way, either of doing it
without recourse to explicit JavaScript, or, better still, to keep
observers automatically attached to elements by id even after they have
been replaced.

Michael


Michael S.
mailto:[email protected]
http://www.schuerig.de/michael/

I think the standard helpers are available in RJS templates so you can
probably just do:

page << observe_field(:foo, options_hash)

And I don’t think you can automatically have the observer work since the
observer actually modifies the form element you are observing. Replace
that html and those modifications are gone too, so it must be recreated.
I think that’s how it works anyway.

On Thursday 31 August 2006 06:52, Alex W. wrote:

Michael S. wrote:

page << “new Form.Element.Observer(‘my_select_element’,” +
" function(element, value) { … });"

That doesn’t feel right. Is there no better way, either of doing it
without recourse to explicit JavaScript, or, better still, to keep
observers automatically attached to elements by id even after they
have been replaced.

I think the standard helpers are available in RJS templates so you
can probably just do:

page << observe_field(:foo, options_hash)

Hm, an earlier reply I sent through the web interface of my mail account
apparently didn’t make it. Yes, indeed, the helpers are available, but
in this case they insert script tags around the generated JavaScript
code. That’s not really what I want to have in an RJS response.

Michael


Michael S.
mailto:[email protected]
http://www.schuerig.de/michael/