Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Simplify with many-keys-map #16

Merged
merged 6 commits into from
Mar 20, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
35 changes: 11 additions & 24 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,56 +1,43 @@
'use strict';
const PCancelable = require('p-cancelable');
const ManyKeysMap = require('many-keys-map');

const targetCache = new WeakMap();

const cleanCache = (target, selector) => {
const map = targetCache.get(target);
if (map) {
map.delete(selector);
if (map.size === 0) {
targetCache.delete(target);
}
}
};
const cache = new ManyKeysMap();

const elementReady = (selector, options) => {
options = Object.assign({
const {target} = Object.assign({
target: document
}, options);

if (targetCache.has(options.target) && targetCache.get(options.target).has(selector)) {
return targetCache.get(options.target).get(selector);
let promise = cache.get([target, selector]);
if (promise) {
return promise;
}

let alreadyFound = false;
const promise = new PCancelable((resolve, reject, onCancel) => {
promise = new PCancelable((resolve, reject, onCancel) => {
let rafId;
onCancel(() => {
cancelAnimationFrame(rafId);
cleanCache(options.target, selector);
cache.delete([target, selector], promise);
});

// Interval to keep checking for it to come into the DOM
(function check() {
const el = options.target.querySelector(selector);
const el = target.querySelector(selector);

if (el) {
resolve(el);
alreadyFound = true;
cleanCache(options.target, selector);
cache.delete([target, selector], promise);
} else {
rafId = requestAnimationFrame(check);
}
})();
});

// The element might have been found in the first synchronous check
if (!alreadyFound) {
if (targetCache.has(options.target)) {
targetCache.get(options.target).set(selector, promise);
} else {
targetCache.set(options.target, new Map([[selector, promise]]));
}
cache.set([target, selector], promise);
}

return promise;
Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
"check"
],
"dependencies": {
"many-keys-map": "^1.0.0",
"p-cancelable": "^1.1.0"
},
"devDependencies": {
Expand Down