简体   繁体   English

从jQuery回调引用CoffeeScript中的父类

[英]Referencing parent class in CoffeeScript from a jQuery callback

I'm new to CoffeScript and I was wondering if there's a way of writing the following piece of code without referencing the global variable app: 我是CoffeScript的新手,我想知道是否有一种方法可以在不引用全局变量应用程序的情况下编写以下代码:

class App 

    constructor: ->
        @ui = ui.init()
        $('#content-holder a[rel!=dialog]').live 'click', ->
            link = $(@).attr 'href'
            app.loadUrl link
            return false

    loadUrl: (href) ->
        # ...

app = new App()

Using the fat arrow doesn't work, as then I lose reference to the jQuery object, ie 使用胖箭头不起作用,因为我失去了对jQuery对象的引用,即

class App   
    constructor: ->
        @ui = ui.init()
        $('#content-holder a[rel!=dialog]').live 'click', =>
            # @ now references App
            link = $(@).attr 'href'
            this.loadUrl link
            return false

    loadUrl: (href) ->
        # ...

The first piece of code works, but I want to get rid of the global variable if possible :-) 第一段代码可以工作,但如果可能的话我想摆脱全局变量:-)

Cheers, Gaz. 干杯,加兹。

Your click handler gets an event passed in... so you can get the best of both worlds with the "fat arrow" without the need to also reference self : 您的点击处理程序会传入一个事件...所以您可以使用“胖箭”获得两个世界中最好的,而无需引用self

constructor: ->
    @ui = ui.init()
    $('#content-holder a[rel!=dialog]').live 'click', (e) =>
        link = $(e.target).attr 'href'
        @loadUrl link
        return false

Well, CS is just a higher-level syntax for JS. 好吧,CS只是JS的更高级语法。

In JS this can only reference a single object. 在JS中, this只能引用单个对象。

The fat arrow uses closure to make this equal to a higher level this , nothing more, and that's why it overrides this in a callback's scope 脂肪箭头使用闭合,使this等于向更高层次发展this ,仅此而已,这就是为什么它会覆盖this在回调的范围

The plain arrow, in contrary, is just a function alias, and that's why this is a DOM element in the first case. 相反,普通箭头只是一个function别名,这就是为什么在第一种情况下this是一个DOM元素。

Finally, @something is trivially translated to this.something , and does nothing more. 最后, @something被简单地翻译成this.something ,并且什么也没做。

So, my opinion - your best choice is really doing self = @ before the binding. 所以,我的意见 - 你最好的选择是在绑定之前做self = @

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

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