【问题标题】:Access class properties and methods from onclick event从 onclick 事件访问类属性和方法
【发布时间】:2013-09-24 05:13:20
【问题描述】:

我是 coffeescipt 的新手,我想创建类,但是有一个问题,当我在按钮上创建“单击”操作时,我如何访问类属性?和其他类函数??

 用更好的类示例编辑问题

感谢这两个回复,问题是: 我只有一个文件,暂时不会有那么多 javascript,所以,我想创建一个类,并按部分分隔“对象”,让我举一个更好的例子:

class SiteName
  isMenuActive: false
  cartItems: {}

  constructor: ->
    that = @
    $('.openMenu').on 'click', ->
     that.menu.open()

  menu:
    open: () ->
      # How can i access "isMenuActive" Here??
      # using @ or this, is referer to the item itself, because this action is called with "onclick"
      if isMenuActive 
        alert 'menu is active'

    close: () -> console.log 'close menu'
    other_action: () -> console.log 'blah'
    call_cart_actions: () ->
      # how can i call cart properties/functions from "cart" in this same namespace??

  cart:
    add: () -> 
      # how to access SiteName.cartItems ¿?
      # How to call other class function??
    remove: () ->

我真正遇到的问题是,我喜欢将所有“触发器”(单击、悬停......)放在构造函数中,但是,一旦我调用这些函数,我如何引用“SiteName”属性或其他对象/该类/命名空间的函数??

这样的代码是个好习惯??将“菜单”和“购物车”放在同一个“站点”类上,还是最好将它们放在文件/类上分开??

非常感谢

【问题讨论】:

  • 为什么需要额外的func 命名空间? “actions 是私有的”是什么意思?
  • 谢谢你们两个,我已经改进了我的问题

标签: javascript jquery coffeescript


【解决方案1】:

根据我所做的一些研究,特别是这个 SO 问题有所帮助:

Coffeescript classes and scope and fat and thin arrows

看起来您需要将 this 引用存储为构造函数的一部分。这是我为演示而整理的代码的破解版本:

class actions
  isActive: false
  self = {}

  constructor: ->
      self = @

  func:
    click: () ->
      alert self.isActive
    close: () ->
      console.log "close function"

f = new actions
f.func.click()

【讨论】:

  • 谢谢 Jason,这是一个很好的解决方案,直到我找到更好的方法或者我会使用你的其他解决方案。
  • 是的,可能有一种 CoffeeScript 方法可以做到这一点,但我找不到任何指出这一点的文档。
猜你喜欢
  • 1970-01-01
  • 2011-08-11
  • 1970-01-01
  • 1970-01-01
  • 2021-11-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多