2013-06-12 33 views
1

我正在創建一個小型的博客應用程序來學習Rails - 用戶可以登錄,創建帖子並對其他用戶帖子發表評論。現在,我將Ajax添加到「添加評論」頁面,並在途中遇到了一些設計問題。頁面流是這樣的:Rails - 添加AJAX時減少耦合

# post section 
:post.title here 
:post.username here 
:post.created_at here 
:post.body here 

# comments section (sorted by date of creation): 
:number of comments here 

:first comment 
:second comment 
... 
:last comment 

# add comment section 
:text_area here 
:submit button here 

的問題:

1 - 的意見是通過創建日期排序,所以我的Ajax調用增加了新的註釋 到頁面的頂部。如果我改變了排序行爲,ajax代碼就壞了。

2 - 評論div可以有3個CSS類:.odd,.even或.admin(如果評論由管理員用戶創建,則應用循環奇數/偶數或管理員)。 現在我很難編碼這些類名,並使用一些如果得到正確的。這也不好,如果改變了css類的名字,ajax代碼就壞了。

我該如何避免這些事情,或至少改善? 這是我的create.js.erb:

var div = $('#comments_div'); 
var comment_class = div.children().first().attr('class') 
var new_class; 

<% if current_user.admin == 1 %> 
    new_class = 'comment_body_admin' 
<% else %> 
if (comment_class === 'comment_body_odd') 
    new_class = 'comment_body_even' 
else 
    new_class = 'comment_body_odd' 
<% end %> 

var new_div = $('#comments_div').prepend("<%= j render @comment %>"); 
new_div.children().first().attr('class', new_class) 

感謝您的幫助!

回答

0

1 - 您將如何更改註釋排序,而不是反轉創建的排序?在這種情況下,您需要使create.js.erb知道排序順序並使用append而不是prepend。

2 - 爲管理員應用「管理員」類,但將奇數條形圖留給CSS。像這樣的東西應該做到這一點:

.comment:nth-child(2n) { background: #eeeeee; } 

而且它是更有效地建立自己的節點,並操縱其屬性,將其插入到DOM前:

var comment = $("<%= j render @comment %>").addClass('comment') 
comment.addClass(new_class) 
$('#comments_div').prepend(comment) 
+0

關於項目2,我該怎麼辦那?我有一個@comment部分,所以偶數/奇數週期會在每個Ajax調用中重置。並感謝DOM提示! – Fernando

+0

我更新了答案。 Google有很多關於CSS3斑馬條紋的教程。 – davidfurber

+0

哼哼...現在我明白了,謝謝! – Fernando