繁体   English   中英

通过onclick事件访问类属性和方法

[英]Access class properties and methods from onclick event

我是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”属性或其他对象/函数该类/命名空间?

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

非常感谢

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

Coffeescript类别和范围以及粗细箭头

看来您需要this引用存储为构造函数的一部分。 这是我汇总的代码的骇客版本:

class actions
  isActive: false
  self = {}

  constructor: ->
      self = @

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

f = new actions
f.func.click()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM