observe_field in rails

There used to be this method observe_field in rails upto v2.3.8 under ActionView::Helpers::PrototypeHelper. To give more details – here is the snipper from apidock

observe_field(field_id, options = {}) public

Observes the field with the DOM ID specified by field_id and calls a callback when its contents have changed. The default callback is an Ajax call. By default the value of the observed field is sent as a parameter with the Ajax call.

You need to specify url for the ajax call / a javascript function that you want to execute on the change of the field. Additional options give you flexibility to specify how frequently the action is supposed to take place, options to specify more parameters to the ajax call. 
The use case for this is something like selecting from a dropdown, and updating some content on the page based on the selection. 

However the caveat here is, you cannot do something like the jQuery live functionality. If you have more select boxes coming up later after the page has already loaded, your ajax calls won’t happen on selecting something from the new dropdown. 

Secondly this seems to work only for the change event on fields although on dom elements I would like to have reused the same method for multiple other events like ‘click’, ‘mouseover’, and so many more.

In addition, there is an observe_form method that can help out a bit with the 1st problem by observing all fields within the form for changes, however with dynamic elements (not in the original source of the form) coming up it again fails. (Jquery has made life so much easier and natural rather than trying out weird solutions to do stuff like this.)

So whats up with this method now?

This method has been deprecated. In fact the PrototypeHelper has seen a lot of change. Legacy prototype helpers are available as a plugin now. https://github.com/rails/prototype_legacy_helper in favour of making Rails 3 agnostic of javascript frameworks.

Ofcourse, jQuery can handle the above scenarios with much more flexibility and cleaner code. 

So if you are upgrading a legacy project which has usages of observe_field, it would be advisable to go for jQuery and keep it clean, simple and working 🙂


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s