如何在jQuery $ .bind()中使用Coffeescript’the’?

在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的调用会产生以下错误:

未捕获的TypeError:对象#没有方法’下注’

所以,目前我的类的实例方法没有被调用,如何在没有与jQuery选择器碰撞的情况下正确调用我的类的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-arrow,然后你的范围就像你在placeBet函数中一样。 然后,您将使用e.currentTarget来获取对目标对象的引用,而不是使用$(this)

 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!' 

你的脚本变成了这个:

 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; })(); 

你需要的是对_self的引用,它是Bet对象:

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