之前我們通過“javascript_include_tag”引入了一些JavaScript的庫文件。其中有一個是effects.js的庫文件。這個庫文件爲我們提供了很多視覺效果的實現,其中有一個叫做“Yellow Fade Technique”的效果,正式我們這次所需要的。這個效果是使用指定的開始顏色高亮指定的對象,然後漸漸消退,直到到達終了顏色結束。並使得指定對象的背景色恢復到高亮前的狀態。
要實現這個效果,我們必須讓程序知道我們要高亮的對象是哪個。而我們現在的程序是不知道的。所以在使用這個效果之前,我們需要做一些準備工作。
首先,我們需要修改depot/app/models/cart.rb文件,讓Cart類記錄下來當前添加的是哪個產品。
def add_product(product)
current_item = @items.find {|item| item.product == product}
if current_item
current_item.increment_quantity
else
current_item = CartItem.new(product) <= New
@items << current_item <= Modified
end
current_item <= New
end
接下來我們需要修改depot/app/controllers/store_controller.rb文件的add_to_cart方法,把Cart的add_product方法返回的對象保存到一個屬性中。
def add_to_cart
product = Product.find(params[:id])
@cart = find_cart
@current_item = @cart.add_product(product) <= Modified
respond_to do |format|
format.js
end
rescue ActiveRecord::RecordNotFound
logger.error("Attempt to access invalid product #{params[:id]}")
redirect_to_index("Invalid product")
end
然後修改depot/app/views/store/_cart_item.html.erb文件來使用這個屬性。
<% if cart_item == @current_item %> <= New
<tr id="current_item"> <= New
<% else %> <= New
<tr>
<% end %> <= New
<td><%=h cart_item.title %></td>
<td>×<%= cart_item.quantity %></td>
<td class="item-price"><%= number_to_currency(cart_item.price) %></td>
</tr>
最後,在depot/app/views/store/add_to_cart.js.rjs文件最後添加如下代碼來使用我們需要的高亮效果。
page[:current_item].visual_effect :highlight,
:startcolor => "#88ff88",
:endcolor => "#114411"
好了,我們需要的效果就做好了。