Fresheyeball
Fresheyeball

Reputation: 30015

Access a parent class for contained class in coffeescript

 class ChildItem
     constructor : ->
         @activate()
     activate : ->
         if parent.ready #this line will fail
            console.log 'activate!'

  class ParentItem
     constructor : ->
        @ready = true;
        @child = new ChildItem()

  item = new ParentItem()

How can I access item.ready from item.child.activate ? There has got to be a syntax for this!

Upvotes: 0

Views: 55

Answers (2)

phenomnomnominal
phenomnomnominal

Reputation: 5515

There's no syntax for magically accessing that unfortunately... Even something like arguments.caller wouldn't help here. However there are a couple of ways you can do it, not sure which you prefer:

1) Pass the ready argument in (or alternatively you could pass in the whole parent).

class ChildItem
   constructor: (ready) ->
     @activate ready
   activate: (ready) ->
     if ready
        console.log 'activate!'

class ParentItem
   constructor : ->
      @ready = true
      @child = new ChildItem(@ready)

item = new ParentItem()

2) Or you could use extends which would give the ChildItem access to all the properties and functions of the ParentItem:

class ParentItem
   constructor : (children) ->
      @ready = true
      @childItems = (new ChildItem() for child in [0...children])

class ChildItem extends ParentItem
   constructor: ->
     super()
     @activate()
   activate: ->
     if @ready
        console.log 'activate!'

item = new ParentItem(1)

Upvotes: 1

mu is too short
mu is too short

Reputation: 434685

No, there isn't a special syntax for this. If you need a relationship between a ChildItem and a ParentItem then you have to hook it up yourself; for example:

class ChildItem
    constructor: (@parent) ->
        @activate()
    activate: ->
        console.log('activate') if(@parent.ready)

class ParentItem
    constructor: ->
        @ready = true
        @child = new ChildItem(@)

item = new ParentItem()

Upvotes: 1

Related Questions