使用 coffeescript 访问 class 实例和 jQuery 的实例

Access both class instance and jQuery's this with coffeescript

我正在实施一个基本的 "shopping Cart",您可以在其中更改产品并重新计算总价。

我想访问 实例 jQuery 的 this 同一方法中的实例,特别是 product_change().

class Cart
  constructor: ->
    @bind_listeners()
  bind_listeners: ->
    $('td.product').on 'change', 'select',@product_change
  update_prices: ->
    # For each row of items get span.subtotal and sum
    # Replace content of "total" field with result
  product_change: ->
    # Get new product's price. I need jQ's 'this'
    new_price = $(this).find ':selected'
    # Replace subtotal field
    $('span.subtotal').html new_price
    # Update all prices. I need instance's 'this'
    @update_prices()

我现在的工作解决方案是调用 update_prices 作为 change 事件的另一个绑定方法,使用粗箭头 =>。但是我宁愿有一个更漂亮的选择。

class Cart
  constructor: ->
    @bind_listeners()
  bind_listeners: ->
    $('td.product').on 'change', 'select',@product_change
    # Call update_prices here
    $('td.product').on 'change', 'select',@update_prices
  update_prices: ->
    # For each row of items get span.subtotal and sum
    # Replace content of "total" field with result
  product_change: ->
    # Get new product's price. I need jQ's 'this'
    new_price = $(this).find ':selected'
    # Replace subtotal field
    $('span.subtotal').html new_price
    # Update all prices. I need instance's 'this'
    #@update_prices()

不使用 jQuery 在调用事件处理程序时设置的 this 的值,而是使用传递给事件处理程序的目标 jQuery。它们都是同一个对象:触发事件的 DOM 元素。

因此您的代码变为:

class Cart
  constructor: ->
    @bind_listeners()
  bind_listeners: ->
    $('td.product').on 'change', 'select', @product_change.bind(@)
  update_prices: ->
    # For each row of items get span.subtotal and sum
    # Replace content of "total" field with result
  product_change: (e) ->
    # Get new product's price. I need jQ's 'this'
    new_price = $(e.currentTarget).find ':selected'
    # Replace subtotal field
    $('span.subtotal').html new_price
    @update_prices()

(请注意,我使用 .bind 来防止 this 的值在 jQuery 调用 product_change 时被覆盖。您也可以定义=> 方法完成同样的事情。)

在方法中使用 this 来一致地引用这些方法所附加的对象,而不是其他东西,将使您作为 CoffeeScripter 的生活变得更加轻松。