Skip to content

Instantly share code, notes, and snippets.

@mohamedmansour
Created April 14, 2012 05:28
Show Gist options
  • Save mohamedmansour/2382261 to your computer and use it in GitHub Desktop.
Save mohamedmansour/2382261 to your computer and use it in GitHub Desktop.
MutationSummary example for MutationObservers
// Keep track of the observers so we could clean up.
var previousObserver = null;
var currentObserver = null;
// Observe when the stream panel has changed. In Google+, the streampanel gets
// swapped when viewing another stream. It gets added, old one gets removed, and
// the new one's visibility is shown.
var summaryObserver = new MutationSummary({
callback: handleChanges,
queries: [{ element: "div[guidedhelpid='streamcontent']" }]
});
// This would check if it found any streamcontents, if so, it preserves the
// observer so we could later one remove it when this streamcontents changes.
function handleChanges(summaries) {
var attributeSummary = summaries[0];
if (attributeSummary.added.length === 1) {
// Save the current observer, since we need to cleanup after this element
// gets removed.
previousObserver = currentObserver;
// Replace the current observer with the new one which observes the update
// changes. We need to keep track of all the items within the stream.
var streamContent = attributeSummary.added[0];
currentObserver = new MutationSummary({
callback: handleUpdateChanges,
rootNode: streamContent,
queries: [{ element: "*" }]
});
}
else if (attributeSummary.removed.length === 1) {
// When an a streamcontent has been removed, deattach all observer listeners
// that we were listening. In this case, we just disconnect the previous
// observer to cleanup.
if (previousObserver) {
previousObserver.disconnect();
console.log('Disconnected');
}
}
}
// This would check if new DOM elements are shown that have that begins
// with "update-". Usually this should contain many added summaries.
function handleUpdateChanges(summaries) {
var elementSummaries = summaries[0];
for (var i = 0; i < elementSummaries.added.length; i++) {
var addedElement = elementSummaries.added[i];
if (addedElement.id && addedElement.id.indexOf('update-') === 0) {
console.log('NEW_ITEM', addedElement.id);
}
}
}
@tzafrir
Copy link

tzafrir commented Apr 15, 2012

Bless you, I wasted a lot of time yesterday on trying to understand what's going on with the way the new UI injects posts.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment