views:

465

answers:

7

I'm working on an AJAXy project (Dojo and Rails, if the particulars matter). There are several places where the user should be able to sort, group, and filter results. There are also places where a user fills out a short form and the resulting item gets added to a list on the same page.

The non-AJAXy implementation works fine -- the view layer server-side already knows how to render this stuff, so it can just do it again in a different order or with an extra element. This, however, adds lots of burden to the server.

So we switched to sending JSON from the server and doing lots of (re-)rendering client-side. The downside is that now we have duplicate code for rendering every page: once in Rails, which was built for this, and once in Dojo, which was not. The latter is basically just string concatenation.

So question part one: is there a good Javascript MVC framework we could use to make the rendering on the client-side more maintainable?

And question part two: is there a way to generate the client-side views in Javascript and the server-side views in ERB from the same template? I think that's what the Pragmatic Programmers would do.

Alternatively, question part three: am I completely missing another angle? Perhaps send JSON from the server but also include the HTML snippet as an attribute so the Javascript can do the filtering, sorting, etc. and then just insert the given fragment?

+1  A: 

Well, every time you generate HTML snippets on the client and on the server you may end up with duplicated code. There is no good way around it generally. But you can do two things:

  1. Generate everything on the server. Use AHAH when you need to generate HTML snippets dynamically. Basically you ask server to generate an HTML fragment, receive it asynchronously, and plug it in place using innerHTML or any other similar mechanism.
  2. Generate everything on the client (AKA the thick client paradigm). In this case even for the initial rendering you pass data instead of pre-rendered HTML, and process the data client-side using JavaScript to make HTML. Depending on the situation you can use the data island technique, or request data asynchronously. Variant: include it as <script> using JSONP so the browser will make a request for you while loading the page.

Both approaches are very simple and have different set of pros and cons. Sometimes it is possible to combine both techniques within one web application for different parts of data.

Of course you can go for exotic solutions, like using some JavaScript-based server-side framework. In this case you can share the code between the server and the client.

Eugene Lazutkin
1. AHAH doesn't let you do things like filtering, sorting, or grouping unless you parse the HTML returned. The parsing can be pretty simple, since you can create arbitrary HTML classes, but that still seems a bit wasteful.2. doesn't solve the duplication problem if I need to support non-JS.
James A. Rosen
1. It depends what kind of hooks did you generate in your snippet. Custom attributes + dojo.query() can do wonders. 2. If you don't have JS on the client --- what kind of code duplication are we talking about? On the server?
Eugene Lazutkin
A: 

I don't have a complete answer for you; I too have struggled with this on a recent project. But, here is a thought:

  • Ajax call to Rails
  • Rails composes the entire grid again, with the new row.
  • Rails serializes HTML, which is returned to the browser.
  • Javascript replaces the entire grid element with the new HTML.

Note: I'm not a Rails person, so I'm not sure if those bits fit.

Chase Seibert
Sure, it works. But that's a lot of overhead on the server every time I choose to sort a table by a different column. Not to mention bandwidth limitations.
James A. Rosen
A: 

Has anyone tried something like the following? There's redundant data now, but all the rendering is done server-side and all the interaction is done client-side.

Server Side:

render_table_initially:
  if nojs:
    render big_html_table
  else:
    render empty_table_with_callback_to_load_table


load_table:
  render '{ rows: [
    { foo: "a", bar: "b", renderedHTML: "<tr><td>...</td></tr>" },
    { foo: "c", bar: "d", renderedHTML: "<tr><td>...</td></tr>" },
    ...
  ]}'

Client side:

dojo.xhrGet({
  url: '/load_table',
  handleAs: 'json',
  load: function(response) {
    dojo.global.all_available_data = response;
    dojo.each(response.rows, function(row) {
      insert_row(row.renderedHTML);
    }
  }
});

Storing the all_available_data lets you do sorting, filtering, grouping, etc. without hitting the server.

I'm only cautious because I've never heard of it being done. It seems like there's an anti-pattern lurking in there...

James A. Rosen
A: 

"Perhaps send JSON from the server but also include the HTML snippet as an attribute so the Javascript can do the filtering, sorting, etc. and then just insert the given fragment?"

I recommend keeping the presentation layer on the client and simply downloading data as needed.

For a rudimentary templating engine, you can extend Prototype's Template construct: http://www.prototypejs.org/api/template

As your client scales and you need a rich and flexible MVC, try PureMVC. http://puremvc.org/content/view/102/181/

Geoff
I have done this with success on a recent project. The main tradeoffs are A) no fall back for non-JS browsers B) potential performance issues (IE6/7) rendering large HTML
Chase Seibert
A: 

As in regular server side programming you should strive to encapsulate your entities with controls, in your case client side controls that has data properties and also render methods + events.

So for example lets say you have on the page an are that shows tree of employees, effectively you should encapsulate it behavior in a client side class that can get JSON object of the employee list / by default connect to the service and a render method to render the output, events and so on.

In ExtJS its is relatively easy to create these kind of controls - look at this article.

A: 

Maybe I'm not fully understanding your problem but this is how I would solve your requirements:

Sort, Filter

It can be done all in JavaScript, without hitting the server. It's a problem of manipulating the table rows, move rows for sorting, hide rows for filtering, there is no need for re-rendering. You will need to mark columns with the data type with custom attributes or extra class names in order to be able to parse numbers or dates.

If your reports are paginated I think it's easier and better to refresh the whole table or page.

Group

I can't help here as I don't understand how will you enable grouping. Are you switching columns to show accumulates? How do you show the data that doesn't support accumulates like text or dates?

New item

This time I would use AJAX with a JSON response to confirm that the new item was correctly saved and possibly with calculated data.

In order to add the new item to the results table I would clone a row and alter the values. Again we don't need to render anything in client-side. The last time I needed something like this I was adding an empty hidden row at the end of the results, this way you will always have a row to clone no matter if the results are empty.

Serhii
A: 

Number 5 in my list of five AJAX styles tends to work pretty well.

James A. Rosen