Last active
July 3, 2016 21:25
-
-
Save vikki/0eb5bbef5cd1334e2b4a1e5039ad33a5 to your computer and use it in GitHub Desktop.
Element Poller + chooser - Streams based, returns all results (found + not found) http://jsbin.com/calekubavi/edit?js,console,output
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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 >= NUMBER_OF_PLACEMENTS_REQUIRED; | |
} | |
var allElementsSource = Rx.Observable.combineLatest(pollers) | |
.distinct() | |
.filter(areElementsFound) | |
.take(1) | |
.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