Montag, 6. Oktober 2008

Javascript and RJS

To descide how to handle javascript in ruby you should seperate between.

1. Effects (hide, show, highlight, fade ect), and
2. Interactive data (with or without visual effects)
3. Embedding Javascript the good old way.

1. Effects
Visual effects being anything that just tells the client side javascript engine to do somthing with one or more its DOM's.

2. Interactive Data
Interactive data, would be somthing like a calculating user input and diplaying the resulting sum in realtime.

3. Embedding Javascript the good old ways
If you like cluttering every things up javascript, you probably should not being using rails. Apart from needing a lot more programming time, and lines of code and making everything a millon times more dificult to test there is no reason what so ever to fall back to embedding javascript in the views as it used to be.

The difference between the 1 and 2 is that in the first case, you don't need to use an RJS file, whereas in the second case you will need and observer and an RJS file to handle the resulting data update when the observer registers user data changes in one or more input fields on a page.

Rails Javascript Engine.
This engine can only do one thing. Wack out javascript to the client side browsers java engine for rendering. The Rails engine has no concept of the state of the page being manipulated by the client side browser java engine.

This means conditionals are not directly possible. i.e.
if page[:input_field_name] == 'red'
:input_field_name] = 'blue'

What you can do is this:
page << "if $(('input_field_name').value == 'red' {" # this is a straight javascript string which does not get interpreted page[:input_field_name]=='blue' # this get turned into a java script statement and sent to the client page << "}"
# this is a straight javascript string which does not get interpreted and finishes the conditional

Note the conditional has nothing to do with rails - the engine in the browser interprests the code output by page.

Keine Kommentare: