如何在 jQuery $.bind() 中使用 Coffeescript 'this'? [英] How can I use Coffeescript 'this' from within jQuery $.bind()?

查看:15
本文介绍了如何在 jQuery $.bind() 中使用 Coffeescript 'this'?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Coffeescript 中使用类时,我偶然发现了一个大问题,让我来说明一下

When using classes in Coffeescript, I've stumbled upon a major problem, let me illustrate

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

The call to this.bet above generates the following error:

Uncaught TypeError: Object # has no method 'bet'

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

So, currently the instance method of my class is not being called, How can I correctly call the bet method of my class without it colliding with the jQuery selector's this (Which is what I suppose is happening now)?

非常感谢您!

推荐答案

试试这个:

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

这篇关于如何在 jQuery $.bind() 中使用 Coffeescript 'this'?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆