4

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.

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

1 Answer 1

5

jQuery's AJAX callbacks are executed in the context of:

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

so @ (AKA this) isn't your Session instance when the callbacks are called. The CoffeeScript-ish way around this is to bind the callback to your Session instance using a fat-arrow:

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, ...

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; 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:

@loginForm.bind 'ajax:before', (xhr, settings) =>
    console.log @loader // --------------------^^
    true
Sign up to request clarification or add additional context in comments.

1 Comment

Excellent. Thank you for the verbose response. The fat arrow is what I was looking for.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.