Skip to content

Commit

Permalink
Merge pull request #115 from canjs/fix-memory-leak
Browse files Browse the repository at this point in the history
Fix memory leak by unbinding on unmount
  • Loading branch information
Christopher Baker authored Apr 27, 2018
2 parents 2fbff9c + b5f0e07 commit 17338e8
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 1 deletion.
3 changes: 2 additions & 1 deletion observer.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ function Observer(onUpdate) {
this.onUpdate = onUpdate;

var self = this;
this.onDependencyChange = function(newVal, oldVal) {
this.onDependencyChange = function onDependencyChange(newVal, oldVal) {
self.dependencyChange(this, newVal, oldVal);
};
}
Expand Down Expand Up @@ -65,6 +65,7 @@ Observer.prototype.dependencyChange = function() {
};

Observer.prototype.teardown = function() {
recorderHelpers.stopObserving(this.newDependencies, this.onDependencyChange);
queues.deriveQueue.dequeue(this.onUpdate);
};

Expand Down
28 changes: 28 additions & 0 deletions test/test.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import QUnit from 'steal-qunit';
import React /*, { Component as ReactComponent } */ from 'react';
import ReactTestUtils from 'react-dom/test-utils';
import DefineMap from 'can-define/map/map';
import canReflect from 'can-reflect';


import reactViewModel from 'react-view-model';
Expand Down Expand Up @@ -200,6 +202,32 @@ QUnit.module('react-view-model', () => {

});

QUnit.test('should remove bound instances when component unmounts', () => {
const Type = DefineMap.extend({en: 'string'});
const greeting = new Type({en: 'hi'});
const calls = [];

canReflect.onInstanceBoundChange(Type, function(instance, isBound){
calls.push( [instance, isBound] )
});

class TestComponent extends Component {
render() {
return <div>{this.viewModel.sayWhat.en}</div>;
}
}

const testInstance = ReactTestUtils.renderIntoDocument( <TestComponent sayWhat={greeting} /> );
const vm = testInstance.viewModel;

// vm change re-renders component, triggering unmount
vm.sayWhat = 'hello';

QUnit.deepEqual( calls, [
[greeting, true],
[greeting, false]
]);
});

});

Expand Down

0 comments on commit 17338e8

Please sign in to comment.