Skip to content

Commit 285bb7a

Browse files
committed
add dispose design pattern, #88
1 parent b9e5262 commit 285bb7a

File tree

1 file changed

+44
-3
lines changed

1 file changed

+44
-3
lines changed

doc/phet-software-design-patterns.md

+44-3
Original file line numberDiff line numberDiff line change
@@ -24,11 +24,52 @@ SR was an advocate of this in https://github.com/phetsims/tasks/issues/952. Clar
2424

2525
## Dispose
2626

27-
when to implement `dispose`, use of `this.dispose{{TypeName}}`, chaining to supertype `dispose`, typical order of disposal
27+
Disposal is the process of freeing up memory so that it can be garbage collected. In javascript disposal can be trickier
28+
than in other languages because it isn't as explicit. A type needs to be disposed if it has any references to undisposed
29+
code outside of its type. For example you need to dispose if you add a listener to an `Emitter` that was passed into
30+
the constructor. You do not need to dispose if a type only effects that type and its children, because it is
31+
self contained and can be garbage collected as a whole.
32+
33+
Once establishing that you need to dispose a type, add the `dispose` method to the prototype. This method should be
34+
`@public` is likely an `@override`. The `dispose` method should do two things, first it should call a private member
35+
function called `this.dispose{{TypeName}}`, and two it should call its parent's dispose method if it has a parent. In
36+
the view it will likely extend from `{{Node}}` and, as such, you will call `Node.prototype.dispose.call( this );` (for es5).
37+
We call "this" type's dispose before the parent's call because we tear down code in the opposite order of construction.
38+
With that last sentence in mind, the safest order of disposal within `this.dispose{{TypeName}}` is the opposite order of
39+
component creation.
40+
41+
Take the following type:
2842

29-
Interested developers: DB, CK, MK
43+
```js
44+
class MyAddChildAndLinkNode extends Node{
45+
constructor( aNode, aProperty){
46+
47+
super();
48+
49+
const aNewNode = new Node();
50+
aNode.addChild( aNewNode );
51+
52+
const aFunction = ()=>{ console.log( 'I love this Property.' )};
53+
aProperty.link( aFunction);
54+
55+
this.disposeMyAddChildAndLinkNode = ()=>{
56+
aProperty.unlink( aFunction);
57+
aNode.removeChild( aNewNode);
58+
}
59+
}
60+
61+
/**
62+
* @override
63+
* @public
64+
*/
65+
dispose(){
66+
this.disposeMyAddChildAndLinkNode();
67+
super.dispose();
68+
}
69+
}
70+
```
3071

31-
TODO: MK will flesh out for 1/21/19
72+
Note that the `Property` is unlinked before the child is removed from the `Node`.
3273

3374
## Enumerations
3475

0 commit comments

Comments
 (0)