[英]Access class properties and methods from onclick event
i'm new on coffeescipt, and i wanted to create classes, but there is a problem, when i create a "click" action on a buttons, how can i access class properties? 我是Coffeescipt的新手,我想创建类,但是有一个问题,当我在按钮上创建“单击”操作时,如何访问类属性? and other class functions?? 和其他类函数?
Thanks for these two replies, the thing is: i have one only file, there will not be so much javascript for now, so, i wanted to create a class, and have separated "objects" by sections, let me put a better example: 感谢这两个答复,问题是:我只有一个文件,目前不会有太多的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: () ->
The problem i reallyhave, is that i like to put all my "triggers" (click, hover...) in constructor, but, once i call these functions, how can i referer to "SiteName" properties or other objects/functions of that class/namespace?? 我真正遇到的问题是,我想将所有“触发器”(单击,悬停...)放入构造函数中,但是,一旦调用这些函数,我该如何引用“ SiteName”属性或其他对象/函数该类/命名空间?
its a good practice to have the code like this?? 拥有这样的代码是一个好习惯? having "menu" and "cart" on same "site" class, or its better to keep them on files/classes separated?? 在同一“站点”类上具有“菜单”和“购物车”,或者最好将它们放在文件/类上分开?
thanks a lot 非常感谢
Based on some research I did, specifically this SO question helped: 根据我所做的研究,这个SO问题特别有帮助:
Coffeescript classes and scope and fat and thin arrows Coffeescript类别和范围以及粗细箭头
it looks like you need to store the this
reference as part of the constructor. 看来您需要this
引用存储为构造函数的一部分。 Here's a hacked version of your code that I put together to demonstrate: 这是我汇总的代码的骇客版本:
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.