开发者

Rails 3 UJS Ajax pattern/strategy, which one is better?

The company I work for has recently upgraded from Rails 2 to Rails 3, during the same period we also migrated from rjs to jquery. We are adop开发者_开发技巧ting a new pattern which is intended to improve view reusability. I will use edit/update as example to illustrate the new way and the old way of doing AJAX in the project:

A. Old way - Edit action template does not render any update specific javascript logic to client. Update template renders both html content and action (replace a element). this is very similar to RJS approach but in jQuery.

Pros:

1. AJAX html content and javascript code that does the DOM manipulation are organized in same .rb file, easy to maintain.

2. View specs can test if proper DOM manipulation js code were rendered in update AJAX response.

Cons:

1. Because html content and js code are coupled and assume certain DOM structure on target page, it's harder to reuse on a different page.

B. New way - the update action template for AJAX request only returns a JSON document, which contains escaped html content. the js code that manipulates DOM is rendered from edit action template and listening on AJAX:success/error virtual event. So the content and behavior are separated.

Pros:

  1. AJAX html content and javascript(behavior) are decoupled, so the content can be tweaked and manipulated slightly different on different page.

Cons:

  1. The html content and js code are now organized in 2 different files (js in edit action template, html content in update action template), it's harder to maintain than before.

  2. We can no longer easily test view behavior - the update template now only render AJAX html content, but the code that manipulates it is in a different view (edit).

  3. Since the response is in JSON format, we can no longer use format to tell if the client is expecting html wrapped in JSON or just JSON API call.

    These are things I have learnt so far, I am wondering if someone with more experience on this topic could shed some light on this - which approach is better in general and how to improve them.

Thanks!

-Xiaotian


jQuery's ajax & rabl to generate json

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜