Skip to content

Instantly share code, notes, and snippets.

@koreus7
Last active March 3, 2017 17:02
Show Gist options
  • Save koreus7/5451e9030a21da47f1d9d6973e1ce6be to your computer and use it in GitHub Desktop.
Save koreus7/5451e9030a21da47f1d9d6973e1ce6be to your computer and use it in GitHub Desktop.
jQuery.fn.futureFind = function futureFind(query, callback) {
function startLooking(el, query, initialElement, localEventID) {
var observer;
function stopLooking() {
observer.disconnect();
}
observer = new MutationObserver(function (mutations) {
var results = el.find(query);
if (results.length > 0) {
if(callback) callback(results);
$(initialElement).trigger(localEventID, [results]);
stopLooking();
}
});
observer.observe(el[0],
{
childList: true,
subtree: true,
attributes: false,
characterData: false
});
}
var initialElement = $(this[0]);
var localEventID = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
});
// If we are not the first in the chain
if (this.eventID) {
// When the one in the chain above us completes start looking.
$(initialElement)
.on(this.eventID,
function (e, results) {
startLooking(results, query, initialElement, localEventID);
this.eventID = localEventID;
});
} else {
// Start looking imedietly because we are the first in the chain.
startLooking(initialElement, query, initialElement, localEventID);
}
// Pass the ID for when this find completes on to the next one in the chain.
this.eventID = localEventID;
return this;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment