如何使用Coffeescript';这';从jQuery$.bind()中?

如何使用Coffeescript';这';从jQuery$.bind()中?,jquery,coffeescript,Jquery,Coffeescript,在Coffeescript中使用类时,我偶然发现了一个主要问题,让我举例说明 class Bet constructor: () -> placeBet: -> $('#chips > div').bind 'click', -> amount = $(this).attr 'id' pile = $(this) switch amount when "ten" then this.bet pile,

在Coffeescript中使用类时,我偶然发现了一个主要问题,让我举例说明

class Bet
  constructor: () ->

  placeBet: ->
    $('#chips > div').bind 'click', ->
      amount = $(this).attr 'id'
      pile = $(this)
      switch amount
        when "ten" then this.bet pile, amount #This line causes a problem

  bet: (pile, amount) ->
    alert 'betting!'
调用上面的this.bet会生成以下错误:

未捕获类型错误:对象没有方法“bet”

所以,目前我的类的实例方法没有被调用, 我如何才能正确调用类的bet方法,而不与jQuery选择器的this发生冲突(我认为现在正在发生这种情况)


提前非常感谢

您的脚本将变成:

var Bet;

Bet = (function() {

  function Bet() {}

  Bet.prototype.placeBet = function() {
    return $('#chips > div').bind('click', function() {
      var amount, pile;
      amount = $(this).attr('id');
      pile = $(this);
      switch (amount) {
        case "ten":
          return this.bet(pile, amount); //<< you cannot do this!!!
      }
    });
  };

  Bet.prototype.bet = function(pile, amount) {
    return alert('betting!');
  };

  return Bet;

})();
试试这个:

class Bet
  constructor: () ->

  placeBet: ->
    that = this
    $('#chips > div').bind 'click', ->
      amount = $(this).attr 'id'
      pile = $(this)
      switch amount
        when "ten" then that.bet pile, amount #This line causes a problem

  bet: (pile, amount) ->
    alert 'betting!'

另一种解决方案是在click事件处理程序中使用CoffeeScript fat箭头,那么您的作用域将与您在placeBet函数中的作用域相同。然后您可以使用
e.currentTarget
来获取对目标对象的引用,而不是使用
$(this)


您不能在jQuery之前将
this
设置为另一个变量吗<代码>变量=这个然后使用
我自己。打赌
只是一个旁注,但如果你不止一次使用它,你真的应该缓存
$(这个)
。@Josh你是说给变量赋值$(这个),然后通过它访问我需要的所有内容吗?我对coffeescript不太熟悉。显然,我会在常规JavaScript中使用
var
,但我在OP的代码中没有看到任何
var
,所以我不确定它是否存在于coffeescript中。太棒了,这很好用。我可以问一件事吗?这样做合适吗?还是有更好的模式来实现这一点?也许甚至Coffeescript也有一个引用自身(类)的语法?我对Coffeescript是100%的新手,所以我只是想知道。。。尽管如此,这是一个伟大的解决方案。也许我早就料到解决这个问题会更困难。这是JavaScript中非常常见的做法。您可以将变量命名为除
以外的其他名称
。我也看过
me
self
\u this
,等等。太棒了!非常感谢您,布拉德利先生。在我的系统中,coffeescript中的绑定函数(例如,
()=>…
编译成使用
\u这个
,所以我个人避免使用它…这个非常酷Sandro!我需要回顾胖箭头是如何工作的,但到目前为止,它仍然让我头疼。感谢你提供了这个解决方案!+1谢谢你,我仍然使用$.proxy的旧方法将其应用到函数调用中。
class Bet
  constructor: () ->

  placeBet: ->
    that = this
    $('#chips > div').bind 'click', ->
      amount = $(this).attr 'id'
      pile = $(this)
      switch amount
        when "ten" then that.bet pile, amount #This line causes a problem

  bet: (pile, amount) ->
    alert 'betting!'
class Bet
  constructor: ->

  placeBet: ->
    $('#chips > div').bind 'click', (e) =>
      target = $(e.currentTarget)
      amount = target.attr 'id'

      switch amount
        when "ten" then @bet target, amount #This line causes a problem

  bet: (pile, amount) ->
    alert 'betting!'