Closed
Description
Summary
for proper memory
renderer type for
potential re-attachment.
Motivation
Currently, Two.js provides a Two.release()
for cleanup, but
There's a need for a
more granular cleanup method that:
- Cleans up renderer-specific resources
- Unbinds all event listeners
- Preserves the renderer type for re-attachment to new
renderers - Provides instance-level cleanup without the Two.js instance
Implementation Details
Base Implementation
Added dispose()
method to Two.Element
base that:
- Preserves renderer type information
- Clears renderer object while maintaining properties
- Unbinds all event listeners
- Returns the instance for method chaining
Enhanced Implementations
Extended dispose()
method for classes additional cleanup:
Two.Path
- Unbinds vertices collection events
- Unbinds individual vertex events and control events
- Unbinds fill/stroke effect events
Two.Group
- Recursively disposes all child objects
- Unbinds children collection events
Two.Text
- Unbinds fill/stroke effect events
Two.Points
- Unbinds vertices collection events
- Unbinds individual vertex events
- Unbinds fill/stroke effect events
Two.ImageSequence
- Stops animation if playing
- Clears animation callbacks
- Unbinds textures collection events
- Unbinds individual texture events
Files Modified
JavaScript Implementation
src/element.js
- Base dispose methodsrc/path.js
- Path-specific dispose methodsrc/group.js
- Group-specific dispose methodsrc/text.js
- Text-specific dispose methodsrc/shapes/points.js
- Points-specific methodsrc/effects/image-sequence.js
ImageSequence-specific dispose
method
TypeScript Definitions
types.d.ts
- Added dispose method signatures all classes
API Usage
// Basic usage
const rect = two.makeRectangle(0, 0, 100, 100);
rect.dispose(); // Cleans up events and resources
// Group with children
const group = two.makeGroup();
group.add(two.makeCircle(0, 0, 50));
group.dispose(); // Recursively disposes all children
// Re-attachment capability
const path = two.makePath();
path.dispose(); // Clean up current renderer
// path.renderer.type is preserved for re-attachment
Benefits
- Memory Management: Proper cleanup memory leaks in
long-running applications - Renderer Flexibility: Objects can be and re-attached to
different renderers - Event Cleanup: Comprehensive unbinding of event listeners
- Performance: Better resource management applications with
many objects - TypeScript Support: Full type definitions better developer
experience
Backward Compatibility
- All changes are additive - no breaking changes
- Existing
Two.release()
method remains unchanged - All dispose methods follow consistent patterns
Documentation
- Complete JSDoc documentation for all methods
- TypeScript definitions with proper return types
Two.js patterns
This feature provides developers with control over resource
cleanup while maintaining the flexibility to reuse objects across
different rendering contexts.