Cameron Barker
Cameron Barker

Reputation: 141

Coffeescript Access Function

I'm new to coffeescript and had a question about accessing functions.

Given the code below how would I access the checkType function from within the constructor's for loop?

class ApplicationForm.Save
  constructor: (@formItems) ->
    @that = this
    for item in @formItems
      do ->
        checkType(item)

   checkType: (forItem) ->
     console.log(@formItem.find("input").length)

Upvotes: 0

Views: 53

Answers (2)

mu is too short
mu is too short

Reputation: 434635

There seems to be a fair bit of confusion here:

  1. @that = this doesn't make any sense. It looks like you're attempting to reproduce the common JavaScript idiom of:

    var that = this;
    

    so that you can use the desired this elsewhere. But @ isn't used for declaring variables (CoffeeScript does that automatically), @ is just shorthand for this.. You're saying this.that = this and that does nothing useful.

  2. do is used in a loop when you need to immediately evaluate the loop variable rather than just grabbing the reference. The common case is something like this:

    for i in [0, 1, 2]
      $(".something#{i}").click -> console.log(i)
    

    That code would just lead to everything saying 2 regardless of what gets clicked because all the anonymous callbacks are using the same i reference. Adding do simply wraps the loop body in a self-invoking function to force the loop variable to dereferenced so this:

    for i in [0, 1, 2]
      do (i) ->
        # do something with `i`...
    

    is like this JavaScript:

    for(i = 0; i <= 2; ++i)
      (function(i) {
        // do something with `i`...
      })(i)
    

    You're passing item to a function already so the do is superfluous.

  3. Your checkType(item) is trying to call a function that doesn't exist. You seem to want to call the checkType method and going back to what @ is all about, we see that you need to use @ to call that method on this:

    @checkType(item)
    
  4. Your checkType method has a forItem argument but you're using @formItem inside the method. But again, @ is just how we say this in CoffeeScript so there seems to be a combination of a typo (forItem versus formItem) and some confusion about what @ means. Your checkType should probably look like:

    checkType: (formItem) ->
      console.log(formItem.find("input").length)
    

Putting all that together gives us:

class ApplicationForm.Save
  constructor: (@formItems) ->
    for item in @formItems
      @checkType(item)
  checkType: (formItem) ->
    console.log(formItem.find("input").length)

Upvotes: 1

andersschuller
andersschuller

Reputation: 13907

You will need to use the fat arrow => in the for loop in order to retain the value of this from the constructor:

for item in @formItems
  do =>
    @checkType(item)

You can read more about the fat arrow syntax in the CoffeeScript documentation.

Upvotes: 0

Related Questions