user1164937 user1164937 - 1 year ago 84
Javascript Question

Unsubscribing to a closed variable inside its own callback

I only want to listen to something once. Is this valid javascript?

const unsubscribe = obj.onFoo(x => {
// do things

Answer Source

Yes, this is a perfectly valid way of calling unsubscribe().

Even though the function is not assigned to the unsubscribe variable until after the function is constructed, it is not run until the callback is called. When the callback is called, it looks for the unsubscribe identifier and finds it in the enclosing scope. The identifier resolves to the unsubscribe function, and so unsubscribe() is called as you would expect.

This is a fairly common pattern. Just one example off the top of my head is clearing a $watch function in AngularJS – Unbinding $watch in angularjs after called

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