Simone Melloni
Simone Melloni

Reputation: 430

coffeescript class variable visibility

I have got something like this:

class @Cat
    defaults:
        name: ''
        weight: 0
    constructor: ( @options ) ->
        $.each @.defaults, (key, val) =>
          @options[key] = val unless @options.hasOwnProperty(key)

i wanna use

$.each (array, callback), (index, value) ->

instead of

$.each (array, callback), (index, value) =>

and use the class variable @options, but obviously @ refers to the array. Solution?

Upvotes: 0

Views: 152

Answers (1)

Dean Radcliffe
Dean Radcliffe

Reputation: 2206

It appears you're having trouble accessing the options that belong to the instance of the class, correct ?

And you know this is because jQuery.each sets this to an object-wrapped version of the val variable, so @options does not work in that callback.

In my example below, the slight change is that I've closed the each callback over the variable opts, which will allow your loop to refer to the contents of @options even though this has been changed.

class Cat
  defaults:
    name: 'tabby'
    weight: 5

  constructor: (@options) ->
    opts = @options
    $.each @defaults, (key, val) ->
      opts[key] = val unless opts.hasOwnProperty(key)

c = new Cat(name: 'fluffy')
console.log c.options

Notice, no double arrow is needed :) In your case, the double arrow wouldn't have hurt since you were accessing the variable val instead of using @ to refer to the value of the current iteration, but you're right to try to get rid of => when not absolutely necessary.

Try it at this fiddle: http://jsfiddle.net/chicagogrooves/72fa3/

That said, I'd like to mention that for the case of overwriting defaults, you could use jquery.extend instead of manually writing your loop. This is a common enough thing to do that it is part of many libraries, not something you need to write by hand usually. But I wanted to explain more thoroughly since double arrows and this are good concepts to know.

Upvotes: 2

Related Questions