Lucas Cordina Lucas Cordina - 2 years ago 63
Javascript Question

Access parent scope inside child element's onclick callback (Atom Package)

I'm not sure how you're normally supposed to handle this within Atom Packages, but this is the situation:

I created a beautiful button

playButton = document.createElement('button');
playButton.onclick = @funkyFreshCallback;

This will call my callback defined as so

funkyFreshCallback: (event, element) ->

Now, what I want is to be able to use the element's parent scope.
See the @ symbol? Right now it returns the button element (because that's the current this, I know)

Now how do I access the scope instead? The same one that defined funkyFreshCallback?

Also, it really doesn't feel like this is how I should be doing things but I haven't found much documentation... at all.

Answer Source

You can bind the parent context onto the function before setting it up as the event handler.

playButton.onclick = @funkyFreshCallback.bind(@);

Another way to avoid the context issue is to setup a function that calls funkyFreshCallback. The event handler should only handle the event and then pass along the minimum set of required data to the callback, like so:

playButton.onclick = (event, element) =>
    timePressed =;

With the code above, funkyFreshCallback will be called with the context that you expect, and won't receive a really complex event object as an argument. This helps to make writing unit tests for funkyFreshCallback easier, and it should simplify your callbacks, because they won't have to deal with events.

More on that in Chapter 7 of Maintainable JavaScript

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download