Skip to content
This repository was archived by the owner on Mar 13, 2018. It is now read-only.

Commit 740d3d3

Browse files
author
John Messerly
committed
Merge pull request #505 from Polymer/observer_leak
fixes #504, avoids global list of all MutationObservers
2 parents 565b978 + 7c8b908 commit 740d3d3

File tree

1 file changed

+16
-13
lines changed

1 file changed

+16
-13
lines changed

src/MutationObserver.js

+16-13
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@
1515
var globalMutationObservers = [];
1616
var isScheduled = false;
1717

18-
function scheduleCallback(observer) {
18+
function scheduleCallback() {
1919
if (isScheduled)
2020
return;
2121
setEndOfMicrotask(notifyObservers);
@@ -26,21 +26,25 @@
2626
function notifyObservers() {
2727
isScheduled = false;
2828

29-
do {
30-
var notifyList = globalMutationObservers.slice();
31-
var anyNonEmpty = false;
29+
while (globalMutationObservers.length) {
30+
var notifyList = globalMutationObservers;
31+
globalMutationObservers = [];
32+
33+
// Deliver changes in birth order of the MutationObservers.
34+
notifyList.sort(function(x, y) { return x.uid_ - y.uid_; });
35+
3236
for (var i = 0; i < notifyList.length; i++) {
3337
var mo = notifyList[i];
3438
var queue = mo.takeRecords();
3539
removeTransientObserversFor(mo);
3640
if (queue.length) {
3741
mo.callback_(queue, mo);
38-
anyNonEmpty = true;
3942
}
4043
}
41-
} while (anyNonEmpty);
44+
}
4245
}
4346

47+
4448
/**
4549
* @param {string} type
4650
* @param {Node} target
@@ -146,7 +150,7 @@
146150
}
147151
}
148152

149-
var anyRecordsEnqueued = false;
153+
var anyObserversEnqueued = false;
150154

151155
// 4.
152156
for (var uid in interestedObservers) {
@@ -180,12 +184,14 @@
180184
record.oldValue = associatedStrings[uid];
181185

182186
// 8.
187+
if (!observer.records_.length) {
188+
globalMutationObservers.push(observer);
189+
anyObserversEnqueued = true;
190+
}
183191
observer.records_.push(record);
184-
185-
anyRecordsEnqueued = true;
186192
}
187193

188-
if (anyRecordsEnqueued)
194+
if (anyObserversEnqueued)
189195
scheduleCallback();
190196
}
191197

@@ -249,9 +255,6 @@
249255
this.nodes_ = [];
250256
this.records_ = [];
251257
this.uid_ = ++uidCounter;
252-
253-
// This will leak. There is no way to implement this without WeakRefs :'(
254-
globalMutationObservers.push(this);
255258
}
256259

257260
MutationObserver.prototype = {

0 commit comments

Comments
 (0)