user1164937 user1164937 - 1 month ago 4x
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


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