UNPKG

@giro3d/giro3d

Version:

A JS/WebGL framework for 3D geospatial data visualization

77 lines (71 loc) 1.87 kB
/* * Copyright (c) 2015-2018, IGN France. * Copyright (c) 2018-2026, Giro3D team. * SPDX-License-Identifier: MIT */ /** * Represents an object that can be shared among multiple instances (multiple ownership). */ export default class Shared { _disposed = false; constructor(_object, _owner, _refCount, _onDispose) { this._object = _object; this._owner = _owner; this._refCount = _refCount; this._onDispose = _onDispose; } /** * The underlying shared object. */ get object() { this.checkDisposed(); return this._object; } /** * Gets the original (first) owner of the shared object. */ get owner() { this.checkDisposed(); return this._owner; } /** * Creates a new shared object with the specified owner. * @param obj - The object to share. * @param owner - The owner of the object. * @param onDispose - The callback to apply when the ref count reaches zero. */ static new(obj, owner, onDispose) { const result = new Shared(obj, owner, { count: 1 }, onDispose); return result; } /** * Clones the reference to the shared object, incrementing the ref count. * Note: this does _not_ clone the shared object itself. */ clone() { this.checkDisposed(); this._refCount.count++; return new Shared(this._object, this.owner, this._refCount, this._onDispose); } checkDisposed() { if (this._refCount.count === 0) { throw new Error('cannot use disposed Shared object'); } } /** * Decrement the ref count of this object. If the count becomes zero, the underlying object is also disposed. */ dispose() { // Idempotence of dispose() if (this._disposed) { return; } this._refCount.count--; if (this._refCount.count === 0) { this._disposed = true; this._onDispose(this._object); } } }