Reputation: 2634
I'm trying to pass a reference to a parent class instance to its child class. The parent class is:
class UI
constructor: (parameters) ->
@addBTS = new AddBTS
@toolbar = new Toolbar(this)
The AddBts and Toolbar classes are:
class Toolbar
constructor: (@parent) ->
add_bts_clickhandler: () =>
$('body').on 'click', '#add_bts', ->
@parent.addBTS.display()
class AddBTS
constructor: () ->
display: () =>
$("#setBuildingTileSet").show()
console.log 'Showing Sir'
All these classes are defined in separate CoffeeScript files and are joined together before comalation in the following order (Game is where the instance of UI lives):
'src/Game'
'src/UI/UI'
'src/UI/AddBTS'
'src/UI/Toolbar'
No, when I call add_bts_clickhandler: ()
I get the error message: * Cannot read property 'addBTS' of undefined *
So it thinks that parent is undefined, when it's clearly not.
Please could someone help me, I'm completely stuck as my code seams fine.
Upvotes: 0
Views: 425
Reputation: 6404
My solution:
I call add_bts_clickhandler:
ui = new window.UI();
ui.toolbar.add_bts_clickhandler();
My classes:
class window.UI
constructor: (parameters) ->
@addBTS = new window.AddBTS
@toolbar = new window.Toolbar(this)
class window.AddBTS
constructor: () ->
display: () =>
$("#setBuildingTileSet").show()
console.log 'Showing Sir'
class window.Toolbar
constructor: (@parent) ->
add_bts_clickhandler: () =>
p = @parent ## introduce a new variable!
$('body').on 'click', '#add_bts', ->
p.addBTS.display(); ##
#@parent.addBTS.display()
Let us look Toolbar class a bit closer:
class window.Toolbar
constructor: (@parent) ->
add_bts_clickhandler: () =>
$('body').on 'click', '#add_bts', ->
@parent.addBTS.display()
Part of the generated javascript:
Toolbar.prototype.add_bts_clickhandler = function() {
return $('body').on('click', '#add_bts', function() {
return this.parent.addBTS.display();
});
};
In this line: return this.parent.addBTS.display();
this refers to the callback function()! not to the add_bts_clickhandler.
I hope I helped you.
Upvotes: 2