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

标签 javascript jquery coffeescript anonymous-function javascript-objects

我熟悉隐藏模式方法论,但我仍然在研究对象原型(prototype)。

我正在尝试创建一个基本类来控制我网站上的一个部分。我遇到的问题是在不同的范围内丢失定义的类变量。例如,下面的代码工作正常,并完美地创建了对象内的属性。然而,当我跳入 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

最佳答案

jQuery 的 AJAX 回调是 executed in the context of :

... an object that represents the ajax settings used in the call ($.ajaxSettings merged with the settings passed to $.ajax)

所以 @(又名 this)在调用回调时不是您的 Session 实例。 CoffeeScript 风格的解决方法是使用 fat-arrow 将回调绑定(bind)到您的 Session 实例。 :

The fat arrow => can be used to both define a function, and to bind it to the current value of this, right on the spot. This is helpful when using callback-based libraries like Prototype or jQuery, ...

我想你想说的是:

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

而且您根本不需要 return 除非您不想取消 AJAX 调用时回调中的最后一条语句可能会意外计算为 false ;如果你想变得偏执(这是一个合理的位置,因为 他们 真的是要抓到我们)那么最后一个简单的 true 就足以得到一个非 false 回调返回的值:

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

关于javascript - 嵌套匿名函数中的 CoffeeScript 类属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9966522/

相关文章:

javascript - React Native onPanResponderMove 似乎很少被调用

javascript - 如何检查 url 是否在 NodeJs 中同步存在?

javascript - 为什么这个 AJAX 请求不能在 JSFiddle 中工作——而它在我的网站上工作正常?

javascript - 来自 mysql、php/JQuery 的 Google 折线图

node.js - 执行 : display stdout "live"

javascript - 提前将Vue组件转换为HTML

javascript - 当显示特定的 div 时设置导航链接的样式

javascript - 如果元素存在,如何阻止 JavaScript 执行?

javascript - CoffeeScript - 如何检索类中的静态数组属性

coffeescript - 与 hasFields 相反的是什么?