Skip to content

Instantly share code, notes, and snippets.

@vikki
Last active July 3, 2016 21:24
Show Gist options
  • Save vikki/c21f527c7ccda19f596c045c4ce5c516 to your computer and use it in GitHub Desktop.
Save vikki/c21f527c7ccda19f596c045c4ce5c516 to your computer and use it in GitHub Desktop.
Element Poller + chooser - Streams based, returns only matched elements (found + not found) - http://jsbin.com/calekubavi/edit?js,console,output
// requires RX.js
const NUMBER_OF_PLACEMENTS_REQUIRED = 1;
const MS_TO_WAIT = 7000;
const selectors = ['.wibble', '.bleuch'];
function checkElement(selector, observer) {
var elementFound = document.querySelector(selector) !== null;
console.log(`el ${selector} = found : ${elementFound}`);
observer.next({found: elementFound, selector: selector});
if (elementFound) {
observer.completed();
}
}
function createElementPoller(selector) {
return Rx.Observable.create(function (observer) {
const intervalId = setInterval(() => checkElement(selector, observer), 1000);
return function unsubscribe() {
if (intervalId) {
clearInterval(intervalId);
}
};
});
}
const pollers = selectors.map(createElementPoller);
function areElementsFound(placementSources) {
console.log('** element changes pushed');
const foundPlacements = placementSources.filter(result => result.found);
return foundPlacements.length >=1;
}
var allElementsSource = Rx.Observable.combineLatest(pollers)
.distinct()
.filter(areElementsFound)
.map(function(matchingResults) {
return matchingResults.filter(result => result.found);
})
.take(NUMBER_OF_PLACEMENTS_REQUIRED)
.timeout(MS_TO_WAIT, 'give up');
var elementListener = allElementsSource.subscribe(
function onNext(outputArray){console.log('output is ', outputArray);},
function onError(err){console.error(err);},
function onComplete(outputArray){console.log('done :)');}
);
// ========================
// next part is for testing it
// you'd normally just let the DOM do this
// ========================
(function addTestElements() {
function addElement(name, delay) {
setTimeout(function() {
var p = document.createElement('p');
p.innerText = name;
p.className = name;
console.log(`^^ adding .${name}`)
document.body.appendChild(p);
}, delay);
};
addElement('wibble', 2000);
addElement('bleuch', 4000);
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment