嵌套匿名函数中的CoffeeScript类属性

Ari*_*ric 4 javascript jquery anonymous-function javascript-objects coffeescript

我熟悉隐藏模式方法,但我仍然围绕对象原型.

我正在尝试创建一个基本类来控制我网站上的某个部分.我遇到的问题是在不同的范围内丢失已定义的类变量.例如,下面的代码工作正常,并在对象内完美地创建属性.但是,当我跳转到jQuery回调时,我失去了所有关于存储一些jQuery对象的类变量的知识以供多种用途.

有没有办法从回调函数中获取它们?

class Session
    initBinds: ->
        @loginForm.bind 'ajax:success', (data, status, xhr) ->
            console.log("processed")
            return
        @loginForm.bind 'ajax:before', (xhr, settings) ->
            console.log @loader // need access to Session.loader
            return
        return
    init: ->
        @loginForm = $("form#login-form")
        @loader = $("img#login-loader")
        this.initBinds()
        return
Run Code Online (Sandbox Code Playgroud)

mu *_*ort 5

jQuery的AJAX回调在以下语境执行:

...表示调用中使用的ajax设置的对象($.ajaxSettings与传递给的设置合并$.ajax)

所以@(AKA this)不是调用回调时的Session实例.CoffeeScript-ish方法是使用fat-arrow将回调绑定到Session实例:

胖箭头=>既可以用来定义一个函数,也可以this在现场将它绑定到当前值.当使用基于回调的库(如Prototype或jQuery)时,这很有用......

我想你想这样说:

@loginForm.bind 'ajax:before', (xhr, settings) =>
    console.log @loader // --------------------^^
    return
Run Code Online (Sandbox Code Playgroud)

return除非你的回调中的最后一个语句可能false在你不想取消AJAX调用时意外地评估,否则你根本不需要它; 如果你想成为偏执(一个合理的位置,因为他们真的是为了得到我们),那么最后一个简单true的就足以false从回调中获得一个非值:

@loginForm.bind 'ajax:before', (xhr, settings) =>
    console.log @loader // --------------------^^
    true
Run Code Online (Sandbox Code Playgroud)