在单独的JS文件中引用Coffeescript事件

时间:2013-07-25 23:21:25

标签: javascript jquery ruby-on-rails dom coffeescript

基本上我已经有了一块咖啡脚,可以动画下拉菜单:

menu_in  = -> $('.cart_pulldown').slideDown(250)
menu_out = -> $('.cart_pulldown').slideU(150)

$('#store_menu').hoverIntent(over: menu_in, out: menu_out, timeout: 150)

我想将其与添加到购物车按钮操作联系起来,以便当用户添加到购物车时发生菜单slideDown / slideUp序列,以下是js代码:

function set_product_page_variant_state() {
var varel = $('div#product-social-links');
var cart_link = $("#add-to-cart-button");
if(varel && cart_link) {
  if(variant_id = varel.attr('data-variant-id')) {
    $.post('/flash_sales/get_state.json', {'variant_ids[]': [variant_id]}, function(data) {
      var state = data[variant_id];
      if(state) {
        if(state=='on_hold') { 
          cart_link.text("On Hold").show();
        } else if(state=='in_my_cart') {
          // TODO: this is funking ugly and slow to load, this whole thing needs a good old fashion refactorin'.
          cart_link.text("In My Cart")
            .hide()
            .after("<a href='/cart' class='action-button add_to_cart' id='#add-to-cart-button'>In My Cart</a>")
            .remove()
        } else if(state=='available') {
          cart_link.removeAttr('disabled').show();
        } else if(state=='sold_out') {
          cart_link.text("Sold Out").show()
        } else {
        // something went wrong, enable the button
          cart_link.removeAttr('disabled').show()
        }
      } else { cart_link.removeAttr('disabled').show() }
    }); 
  } else { cart_link.removeAttr('disabled').show() }
 }
}

只是为了彻底,这里是相关的html:

 <div id="cart-form">
                   <%= form_for :order, :url => spree.populate_orders_url do |f| %>
                     <div id="inside-product-cart-form" itemprop="offers" itemscope itemtype="http://schema.org/Offer">
                       <% if @product.price %>
                         <div>
                           <div class="add-to-cart">
                             <%= hidden_field_tag "variants[#{@variant.id}]", 1 %>
                             <%= button_tag "Add to Cart", :class => "hidden action-button add_to_cart", :type => :submit, :disabled => true, :id => "add-to-cart-button" %>
                           </div>
                         </div>
                       <% end %>
                     </div>
                   <% end %>
                 </div>

非常感谢任何建议,提前谢谢!

2 个答案:

答案 0 :(得分:1)

您可以在Coffeescript文件中使用jQuery委托事件。例如,要在触发menu_out之前显示500毫秒的菜单:

$(document).on 'click', '#add-to-cart-button', (event) ->
  menu_in()
  setTimeout 500, menu_out

答案 1 :(得分:0)

由于CoffeeScript将您的代码放入闭包中,您需要手动将全局变量附加到窗口,例如window.menu_in = -> ...