简体   繁体   English

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

[英]CoffeeScript Class Properties Within Nested Anonymous Functions

I'm familiar with the hidden pattern methodology however I'm still wrapping my head around object prototypes. 我熟悉隐藏模式方法,但我仍然围绕对象原型。

I'm trying to create a basic class for controlling a section on my site. 我正在尝试创建一个基本类来控制我网站上的某个部分。 The problem I'm running into is losing defined class variables within a different scope. 我遇到的问题是在不同的范围内丢失已定义的类变量。 For example, the code below works fine and creates the properties within the object perfectly. 例如,下面的代码工作正常,并在对象内完美地创建属性。 However when I jump into a jQuery callback I lose all knowledge of the class variables storing some of the jQuery objects for multiple uses. 但是,当我跳转到jQuery回调时,我失去了所有关于存储一些jQuery对象的类变量的知识以供多种用途。

Is there a way to grab them from within the callback function? 有没有办法从回调函数中获取它们?

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's AJAX callbacks are executed in the context of : jQuery的AJAX回调在以下语境执行

... an object that represents the ajax settings used in the call ( $.ajaxSettings merged with the settings passed to $.ajax ) ...表示调用中使用的ajax设置的对象( $.ajaxSettings与传递给$.ajax的设置合并)

so @ (AKA this ) isn't your Session instance when the callbacks are called. 所以@ (AKA this )不是调用回调时的Session实例。 The CoffeeScript-ish way around this is to bind the callback to your Session instance using a fat-arrow : CoffeeScript-ish方法是使用fat-arrow将回调绑定到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 ,右当场。 This is helpful when using callback-based libraries like Prototype or jQuery, ... 当使用基于回调的库(如Prototype或jQuery)时,这很有用......

I think you want to say this: 我想你想这样说:

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

And you don't need the return at all unless the last statement in your callback might accidentally evaluate to false when you don't want to cancel the AJAX call; 并且您根本不需要return ,除非您不希望取消AJAX调用时,回调中的最后一个语句可能会意外地评估为false ; if you want to be paranoid (a reasonable position since they really are out to get us) then a simple true at the end would suffice to get a non- false value returned from the callback: 如果你想成为偏执(一个合理的位置,因为他们真的是为了得到我们),那么最后一个简单的true值就足以从回调中得到一个非false值:

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

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

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