v8 Running user-specified code when an Object is garbage collected.


Example

/**
 * Runs user-specified code when the given javascript object is garbage collected
 */
template<class CALLBACK_FUNCTION>
void global_set_weak(v8::Isolate * isolate, const v8::Local<v8::Object> & javascript_object, CALLBACK_FUNCTION function)
{
    struct SetWeakCallbackData{
        SetWeakCallbackData(CALLBACK_FUNCTION function, v8::Isolate * isolate, const v8::Local<v8::Object> & javascript_object) :
            function(function) {
                this->global.Reset(isolate, javascript_object);
        }
        // function to call for cleanup
        CALLBACK_FUNCTION function;

        // this is the weak reference
        v8::Global<v8::Object> global;
    };

    // This must be dynamically allocated so it sticks around until the object
    //   is garbage collected.   It cleans itself up in the callback.
    auto callback_data = new SetWeakCallbackData(function, isolate, javascript_object);

    // set the callback on the javascript_object to be called when it's garbage collected
    callback_data->global.template SetWeak<SetWeakCallbackData>(callback_data,
        [](const v8::WeakCallbackInfo<SetWeakCallbackData> & data) {
            SetWeakCallbackData * callback_data = data.GetParameter();
            callback_data->function(); // run user-specified code
            callback_data->global.Reset(); // free the V8 reference
            delete callback_data; // delete the heap variable so it isn't leaked
        }, v8::WeakCallbackType::kParameter);
}