Accessing both parent object, and calling object, in callback?
-
26-10-2019 - |
Question
I have a library-provided function that runs a callback after some processing.
Inside that callback, I'd like to access the parent object whose method starts that callback - see below.
class MaskMaker
addMaskedImage: (imagefile, texturefile, canvasid) ->
$('<img src="'+imagefile+'">').load ->
console.log('Id like to call another MaskMaker method with @width as a parameter')
Obviously => will give me access to the parent object as this/@, -> will give me access to the element triggering the callback as this/@. But what's the neatest way to do both, eg, so I could call a direct method of MaskMaker with the images width as a parameter? Do I need a that = this hack or is there something better?
Thanks!
Solution
But what's the neatest way to do both, eg, so I could call a direct method of MaskMaker with the images width as a parameter?
You can't choose both (obviously), so would have to go with either =>
+ event.target
$('<img src="'+imagefile+'">').load (ev) => @method ev.target.width
or good ol'
that = this
$('<img src="'+imagefile+'">').load -> that.method @width
See also: https://github.com/jashkenas/coffee-script/issues/1230
OTHER TIPS
If I'm understanding your structure of code completely, you can add a variable that holds a reference to the instance of MaskMaker. Due to scope, you'll be able to see anything further down the chain.
class MaskMaker
var self = this;
addMaskedImage: (imagefile, texturefile, canvasid) ->
$('<img src="'+imagefile+'">').load ->
console.log('Id like to call another MaskMaker method with @width as a parameter')
//self references MaskMaker now, so you can call self.addMaskedImage for example
Define and bind your callback within the scope of MaskMaker:
class MaskMaker
afterAdd => console.log('Id like to call another MaskMaker method with @width as a parameter')
addMaskedImage: (imagefile, texturefile, canvasid) ->
$('<img src="'+imagefile+'">').load -> afterAdd()
Note that I'm using the fat arrow syntax =>
to bind the function stored in afterAdd to MaskMaker.